Java的文件导入导出实现

一. Java文件导出:
1. 文件内容写入DTO

2. 用FacesContext, 取得画面的的Instance(需要Import):

FacesContext faceContext = FacesContext.getCurrentInstance();

3. 取得Response:
HttpServletResponse response = (HttpServletResponse)facesContext.getExternalContext().getResponse();

4. 下载处理
4.1 用path和fileName取得下载文件:
DownloadResponse.writeOther(response, downloadfilepath, downloadfilename);

4.2 读取文件:
BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(downloadFile));
OutputStream outputStream = response.getOutputStream();
int size = inputStream.available();
while(size > 0){
    byte[] bytes = new byte[size];
    inputStream.read(bytes);
    outputStream.write(bytes);
    size = inputStream.available();
}

5. 结束后通知JSF。
facesContext.responseComplete();

二. Java文件导入:
1. 使用fileUpload取得文件的fileByte

2. 将文件内容写入DTO:
String strData = new String(inDTO.getUpload.file_byte(), Charset.forName(SwCharset.TXT_Default.getCharsetName);

3. 作成临时文件,取得路径:
File tempFile = TempFile.create(ID, PageID, strData, SwCharset.UTF8);
// 取得NAS_ID:
String nasID = nasManager.create(ID, PageID, tempFile.getPath(), NASFileType.CSV.getFileType(), "INSERT.csv", "名字");
// 取得NAS文件路径:
String nasFilePath = nasManager.getNasFileInfo(nasID).getAbsolutePath();

4. 用BufferedReader来读取文件:
List> results = new ArrayList>();
BufferedReader reader = new BufferedReader(new FileReader(filePath));
CSVBufferReader inReader = new CSVBufferedReader(reader);
List tmpRow = null;
CSVLineIterator csvLine = inReader.readCSVLine();
while(csvLine != null){
    tmpRow = new ArrayList();
    while(csvLine.hasNext() == true){
        tmpRow.add(csvLine.next());
    }
    resut.add(tmpRow);
    csvLine = inReader.readCSVLine();
}
return result;


你可能感兴趣的:(Java)