public class CreateCSVFile extends BaseDAO{
private static CreateCSVFile _createCSVFile = null;
private FileOutputStream _fos = null;
private StringBuffer _sBuffer = null;
private String _path = "";
public static final String DEL_CHAR = ",";
public static final String AV_CHAR = "\"";
public CreateCSVFile() {
_path = Config.getString("csv_file_path");
this.init(_path);
}
/**
*
* @param path create csv file's path
*/
public void init(String path) {
String method = "createCSVFile_init";
if(path == null || path.trim().equals("")) {
_path = Constant.DEFAULT_PATH;
} else {
_path = path;
}
try {
_fos = new FileOutputStream(_path,false);
_sBuffer = new StringBuffer();
debug("", method, "create csv file sccuessful");
} catch (FileNotFoundException e) {
e.printStackTrace();
debug("", method, "not found exception of create csv file");
}
}
/**
* this method is append date in csv file
* @param data
*/
public void setData(Object data) {
_sBuffer.append(AV_CHAR);
_sBuffer.append(data);
_sBuffer.append(AV_CHAR);
_sBuffer.append(DEL_CHAR);
}
public void writeLine() {
if (_sBuffer.charAt(_sBuffer.length() - 1) == ',')
_sBuffer.delete(_sBuffer.length() - 1, _sBuffer.length());
_sBuffer.append("\r\n");
}
/**
* this method is close fileoutputstream
*/
public void close() {
String method = "close";
try {
if(_sBuffer != null) {
_fos.write(_sBuffer.toString().getBytes());
debug("", method, "close fileOutputStream successful");
} else {
debug("", method, "null point exception");
}
} catch (IOException e) {
debug("", method, "close fileOutputStream failure");
} finally {
try {
if(_fos != null) {
_fos.close();
_fos = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2.Create CSV File Action:
/**
* updateExpired method is update order_history table's attribute(is
* expired) Expired that the <True> value is 0, 1 said that <False>
*
* @param mapping
* @param form
* @param request
* @param response
* @author wuwenqiang
*/
public ActionForward updateExpired(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
String method = "updateExpired";
String createFileMethod = "createFile";
String userId = (String) request.getSession().getAttribute("Portal");
ActionMapping _mapping = null;
List allOrderHistoryList = new LinkedList();
List _orderHistoryList = new LinkedList();
try {
DateManager.getInstance().compareTime(_am.queryALlGlobalSettings());
long startTime = DateManager.getInstance().get_timeMillisStart();
long endTime = DateManager.getInstance().get_timeMillisEnd();
allOrderHistoryList = _am.queryOrderHistoryAll(startTime, endTime);
if (allOrderHistoryList == null || allOrderHistoryList.size() <= 0) {
this.debug(userId, createFileMethod,
Constant.MESSAGE_QUERY_NOELEMENT);
} else {
_orderHistoryList = _ohOperation
.addOrderHistory(allOrderHistoryList);
CreateCSVFile createCSVFile = new CreateCSVFile();
createCSVFile.setData(Constant.RESTAURANT_NAME);
createCSVFile.setData(Constant.MEAL_NAME);
createCSVFile.setData(Constant.MEAL_PRICE);
createCSVFile.setData(Constant.NUM);
createCSVFile.setData(Constant.SUBSCRIBER_NAME);
createCSVFile.setData(Constant.ORDER_TIME);
createCSVFile.writeLine();
for (int i = 0; i < allOrderHistoryList.size(); i++) {
OrderHistory orderHistory = (OrderHistory) allOrderHistoryList
.get(i);
createCSVFile.setData(orderHistory.getMeal()
.getRestaurant().getRestName());
createCSVFile.setData(orderHistory.getMeal().getMealName());
createCSVFile.setData(orderHistory.getMeal()
.getSinglePrice());
createCSVFile.setData(orderHistory.getNum());
createCSVFile.setData(orderHistory.getEmployee()
.getFullName());
createCSVFile.setData(orderHistory.getTime());
createCSVFile.writeLine();
}
createCSVFile.close();
} _am.updateExpired(startTime, endTime);
request.getSession().setAttribute("addOrderHistory_list",_orderHistoryList);
request.setAttribute("flag", "flag_true");
this.debug(userId, method, Constant.LOG_UPDATE_SUCCESS);
return mapping.findForward("list_update");
} catch (ManagerException e) {
e.printStackTrace();
this.error(userId, method, "hibernate exception", e);
}
this.debug(userId, method, Constant.LOG_UPDATE_FAIL);
request.setAttribute("flag", "flag_false");
return mapping.findForward("return_error");
}
3.DownLoad CSV File Action:
/**
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws UnsupportedEncodingException
*/
public ActionForward downloadCSVFile(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) {
String method = "downloadCSVFile";
String userId = (String) request.getSession().getAttribute("Portal");
PrintWriter pw = null;
response.setContentType("application/octet-stream;charset=GBK");
response.setHeader("Content-Disposition",
"attachment; filename=\"mealordering.csv\"");
List allOrderHistoryList = new LinkedList();
String strHead = Constant.RESTAURANT_NAME + "," + Constant.MEAL_NAME
+ "," + Constant.MEAL_PRICE + "," + Constant.NUM + ","
+ Constant.SUBSCRIBER_NAME + "," + Constant.ORDER_TIME;
try {
pw = response.getWriter();
pw.println(strHead);
allOrderHistoryList = (List)request.getSession().getAttribute("addOrderHistory_list");
if (allOrderHistoryList == null || allOrderHistoryList.size() <= 0) {
this.debug("'", method, Constant.MESSAGE_QUERY_NOELEMENT);
} else {
for (Iterator iterator = allOrderHistoryList.iterator(); iterator
.hasNext();) {
OrderHistory orderHistory = (OrderHistory) iterator.next();
String restName = String.valueOf(orderHistory.getMeal()
.getRestaurant().getRestName());
String mealName = String.valueOf(orderHistory.getMeal()
.getMealName());
String mealPrice = String.valueOf(orderHistory.getMeal()
.getSinglePrice());
String num = String.valueOf(orderHistory.getNum());
String subscriber = String.valueOf(orderHistory
.getEmployee().getFullName());
String orderTime = String.valueOf(orderHistory.getTime());
String strLine = "\"" + restName + "\",\"" + mealName
+ "\",\"" + mealPrice + "\",\"" + num + "\",\""
+ subscriber + "\",\"" + orderTime + "\"";
pw.println(strLine);
}
pw.flush();
pw.close();
}
} catch (IOException e) {
e.printStackTrace();
this.debug(userId, method, "IOException");
}
return null;
}
分享到:
相关推荐
2. **Java**:作为广泛使用的编程语言,Java提供了许多库来处理CSV文件,如OpenCSV、Apache Commons CSV或Java 8内置的`java.nio.file.Files`和`java.util.Scanner`。在这个项目中,你可能需要使用这些库来读取CSV...
在给出的代码中,`createCSVFile`方法是生成CSV文件的主要入口。该方法接收四个参数: 1. `exportData`: 这是一个`List`对象,其中包含了要写入CSV文件的实际数据。 2. `map`: 一个`LinkedHashMap`,用于定义CSV...
在Java编程环境中,将本地文件读取并上传到HBase是一项常见的任务,特别是在大数据处理和存储的场景下。HBase是一个分布式、版本化的NoSQL数据库,基于Apache Hadoop,适用于大规模数据存储。以下是一个详细的过程,...
这通常通过编程语言实现,如Python的`csv`库或Java的`BufferedReader`,它们可以处理逗号分隔的值。 2. **数据预处理**:在导入数据库之前,可能需要进行一些预处理操作,如数据清洗(去除空格、处理缺失值)、数据...
- `ENVI_FILE_MNG`管理文件操作,将边界点导出为CSV。 6. **调用MATLAB神经网络工具箱** - 这部分需要额外学习MATLAB和nntool工具箱,用于水质反演。 7. **应用6S大气纠正** - 调用6S程序,对ETM+蓝光波段进行...
在Java编程领域,处理Excel和CSV文件是一项常见的任务,尤其在数据分析、报表生成或数据导入导出时。本文将深入探讨如何使用Java进行Excel读取、数据比较以及CSV相关操作。 首先,Java提供了多种库来处理Excel文件...
除了Apache POI和JExcelAPI,还有其他一些库,如OpenCSV(主要用于CSV文件,但也可处理Excel),以及Spire.XLS Java库,它们提供了不同的特性和使用方式,可以根据项目需求选择合适的工具。 四、性能与选择 Apache...
标题 "利用JAVA代码将本地文件传入HDFS中" 涉及到的是在Java编程环境中,使用Hadoop Distributed File System (HDFS) API来上传本地文件系统的文件到HDFS的过程。HDFS是Hadoop的核心组件之一,它提供了一个分布式、...
BufferedReader br = new BufferedReader(new InputStreamReader(getAssets().open("yourfile.csv"))); String line; while ((line = br.readLine()) != null) { String[] data = line.split(","); // 处理数据...
CREATE TABLE IF NOT EXISTS `txt_data` ( `id` INT AUTO_INCREMENT PRIMARY KEY, `column1` VARCHAR(255), `column2` VARCHAR(255), `column3` VARCHAR(255), -- 其他所需列 ); ``` 这里的`txt_data`是表名,`...
Workbook workbook = WorkbookFactory.create(new File("path_to_your_file.xlsx")); // 遍历工作表 for (Sheet sheet : workbook) { for (Row row : sheet) { for (Cell cell : row) { String cellValue = cell...
例如,`Workbook workbook = WorkbookFactory.create(new File("path_to_your_excel_file"))`。 3. **写入Excel文件**: 创建Sheet对象,然后在Sheet中添加Row和Cell。例如,`Sheet sheet = workbook.createSheet...
// Read CSV file and return list of rows as string arrays } public static <T> Node<T> parseContent(List[]> content, Class<T> valueType) { // Convert parsed content into a tree structure } } ``` ...
Database db = Database.create(new File("new.mdb")); Table newTable = new TableBuilder("NewTable") .addColumn(new ColumnBuilder("a") .setSQLType(Types.INTEGER) .toColumn()) .addColumn(new ...
file UTL_FILE.FILE_TYPE; v_line VARCHAR2(32767); BEGIN -- 创建CSV文件 file := UTL_FILE.FOPEN('YOUR_DIR', filename, 'W', 32767); -- 执行查询 FOR rec IN (EXECUTE IMMEDIATE query) LOOP v_line :...
例如,如果你有一个CSV文件,你可以使用LOAD CSV语句将数据加载到数据库中。 在描述中提到的"src/test/java"目录下的源代码,很可能是用Java编写的测试代码。这些代码可能包含以下关键部分: 1. **数据生成**:这...
df_csv = pd.read_csv(zip_file.open(entry_name, 'r'), encoding='utf-8') # 读取Excel from openpyxl import load_workbook workbook = load_workbook(filename=zip_file.open(entry_name, 'rb')) sheet = ...
File outputFile = new File("output.csv"); FileOutputStream outStream = new FileOutputStream(outputFile); IOUtils.copy(downloadResponse.getEntity().getContent(), outStream); } } ``` 这里的`IOUtils....
2. `createTable(String tableName, List<Column> columns)`: 创建一个新的DBF表,传入表名和字段列表。 3. `writeRecord(DBFRecord record)`: 写入一条记录到当前打开的DBF表中。 4. `close()`: 关闭DBF文件,释放...
其次,Java 8引入了新的内置API,使得处理CSV和Excel文件变得更加简单,尤其是对于小型文件。然而,对于大型Excel文件,由于内存限制,可能仍然推荐使用Apache POI。以下是一个使用Java 8读取Excel文件的例子: ```...