以处理某sql文件为例
源文件中行格式为:
123456 7895433 xxxxx yyyyy zzzzz
行间分隔符为 TAB.
转换完后文件中行的格式为:
123456,7895433,xxxxx,yyyyy,zzzzz
package tool;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
public class TransferFile {
public static void main(String[] args) throws IOException
{
File f=new File("F:/mernis/data_dump.sql");
File filewrite=new File("F:/mernis/mernis-test.txt");
int count=0;
if(f.exists())
{
FileReader read=new FileReader(f);
BufferedReader buff=new BufferedReader(read);
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filewrite, true)));
boolean isEnd=false;
int i=0;
while(!isEnd)
{
String line;
i++;
try {
line = buff.readLine();
if(line==null)
{
isEnd=true;
}
else
{
if (i>=76&&i<=49611784)
{
String[] lineArr = line.split("\\t");
String newline="";
for (int j = 0; j < lineArr.length; j++) {
if (j<lineArr.length) {
newline=newline+lineArr[j]+",";
}
else
newline=newline+lineArr[j];
}
out.write(newline+"\r\n");
}
count++;
// if (i==100) {
// return ;
// }
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("文件共有"+count+"行");
buff.close();
out.close();
}
else
{
System.out.println("你输入的文件不存在,请正确使用:");
}
}
}
TransferFile.java
其中关键代码为:
String[] lineArr = line.split("\\t");
String newline="";
for (int j = 0; j < lineArr.length; j++)
{
if (j<lineArr.length)
{
newline=newline+lineArr[j]+",";
}
else
newline=newline+lineArr[j];
}
过程中曾尝试用line.replace("\\t",",")的方法将TAB替换为",",但是始终不成功,所以这里采用先用TAB分割字符串,再用逗号连接的方式。