背景
说明:在1.0基础上增加对每行的继续处理
代码
package com.zj.commons.fileutils;
import java.io.*;
public class FileUtils {
private static final String fileSourcePath = "输入路径";
private static final String fileOutPath = "输出路径";
/**
* 按行将文件进行解析
*
* @param fileSourcePath 文件输入路径
* @param separator 分隔符格式
* @param fileOutPath 文件输出路径
* @throws IOException
*/
public static void processFile(String fileSourcePath, String separator, String subStringChar, String fileOutPath) throws IOException {
// 保存处理结果
String result = "";
// 读取文件
FileReader fr = new FileReader(new File(fileSourcePath));
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
while (line != null) {
// 去除空行
if ("".equalsIgnoreCase(line.trim())) {
line = br.readLine();
continue;
}
// 继续处理每行的数据
result += processWithSeparator(line, separator, subStringChar);
line = br.readLine();
}
// 写入文件
FileWriter fw = new FileWriter(new File(fileOutPath));
fw.write(result);
fw.flush();
fw.close();
}
private static String processWithSeparator(String line, String separator, String subStringChar) {
line = line.trim();
// 以常见的字符串分隔符进行分割换行单独展示,如:, .
String[] sp = line.split(separator);
String res = "";
for (String item : sp) {
res += processWithSubString(item.trim(), subStringChar) + "\n";
}
return res;
}
private static String processWithSubString(String trim, String subStringChar) {
if ("".equalsIgnoreCase(subStringChar.trim())) {
return trim.trim();
} else {
return trim.trim().substring(trim.trim().indexOf(subStringChar) + 1);
}
}
/**
* test
*
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
processFile(fileSourcePath, ";", "、", fileOutPath);
}
}