txtドキュメント操作(エクスポートとインポート)【キットシリーズ】
4521 ワード
上一篇はCSVの导入を绍介して、今txtの导入を绍介して、両者はとても似ていて、多く绍介しないで、直接コードをつけました
テスト用例を添付しましたので、自分でテストしてください.直接プロジェクトで使用できます.
package com.lwl.util;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
/**
* txt ( )
* @author [email protected]
* @create 2016-4-27 9:47:27
* @version 1.0
*/
public class TextUtils {
/**
*
* @param file Txt ( + ),Txt
* @param dataList
* @param heads
* @return
* @author [email protected]
* @create 2016-4-27 9:49:49
*/
public static boolean exportTxt(File file, List dataList,String heads){
FileOutputStream out=null;
try {
out = new FileOutputStream(file);
return exportTxtByOS(out, dataList, heads);
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
}
}
/**
*
* @param out
* @param dataList
* @param heads
* @return
* @author [email protected]
* @create 2016-4-27 9:49:49
*/
public static boolean exportTxtByOS(OutputStream out, List dataList,String heads){
boolean isSucess=false;
OutputStreamWriter osw=null;
BufferedWriter bw=null;
try {
osw = new OutputStreamWriter(out);
bw =new BufferedWriter(osw);
//
if(heads!=null&&!heads.equals("")){
bw.append(heads).append("\r");
}
//
if(dataList!=null && !dataList.isEmpty()){
for(String data : dataList){
bw.append(data).append("\r");
}
}
isSucess=true;
} catch (Exception e) {
e.printStackTrace();
isSucess=false;
}finally{
if(bw!=null){
try {
bw.close();
bw=null;
} catch (IOException e) {
e.printStackTrace();
}
}
if(osw!=null){
try {
osw.close();
osw=null;
} catch (IOException e) {
e.printStackTrace();
}
}
if(out!=null){
try {
out.close();
out=null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
return isSucess;
}
/**
*
*
* @param file Txt ( + )
* @return
*/
public static List importTxt(File file){
List dataList=new ArrayList();
BufferedReader br=null;
try {
br = new BufferedReader(new FileReader(file));
String line = "";
while ((line = br.readLine()) != null) {
dataList.add(line);
}
}catch (Exception e) {
}finally{
if(br!=null){
try {
br.close();
br=null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
return dataList;
}
/**
*
* @param args
* @author [email protected]
* @create 2016-4-27 10:11:46
*/
public static void main(String[] args) {
//
// List dataList=new ArrayList();
// dataList.add("1, , ");
// dataList.add("2, , ");
// dataList.add("3, , ");
// File file = new File("E:/test");
// if(!file.exists()){
// file.mkdir();
// }
// boolean isSuccess=TextUtils.exportTxt(new File("E:/test/ljq.txt"), dataList," , , ");
// System.out.println(isSuccess);
//
List dataList= TextUtils.importTxt(new File("E:/test/ljq.txt"));
for (String string : dataList) {
System.out.println(string);
}
}
}
テスト用例を添付しましたので、自分でテストしてください.直接プロジェクトで使用できます.