[java]代码库
package test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReadTxtUtils {
/**
* @param args
*/
public static void main(String[] args) {
String regEx = "[' ']+"; // 一个或多个空格
Pattern p = Pattern.compile(regEx);
try {
String encoding = "UTF8"; // 字符编码(可解决中文乱码问题 )
File file = new File("d:/jinzhou.txt");
if (file.isFile() && file.exists()) {
InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);
BufferedReader bufferedReader = new BufferedReader(read);
FileOutputStream out = null;
out = new FileOutputStream(new File("D:/jinzhou1.txt"));
String lineTXT = null;
int count = -1;
while ((lineTXT = bufferedReader.readLine()) != null) {
count += 1;
Matcher m = p.matcher(lineTXT);
String str = count + "," + m.replaceAll(",").trim();
System.out.println(str.substring(0, str.length() - 1));
out.write(str.substring(0, str.length() - 1).getBytes());
}
read.close();
out.close();
} else {
System.out.println("找不到指定的文件!");
}
} catch (Exception e) {
System.out.println("读取文件内容操作出错");
e.printStackTrace();
}
}
}