我正在尝试解析这样的文件:
文本文件.txt
_=1406048396605
bh=1244
bw=1711
c=24
c19=DashboardScreen
c2=2014-07-22T10:00:00-0700
c4=64144090210294
c40=3#undefined#0#0#a=-2#512#-1#0
c41=14060470498427c3e4ed
c46=Green|firefox|Firefox|30|macx|Mac OS X
c5=NONFFA
c6=HGKhjgj
c7=OFF_SEASON|h:PARTIAL|
ch=YHtgsfT
g=https://google.hello.com
h5=77dbf90c-5794-4a40-b1ab-fe1c82440c68-1406048401346
k=true
p=Shockwave Flash;QuickTime Plug-in 7.7.3;Default Browser Helper;SharePoint Browser Plug-in;Java Applet Plug-in;Silverlight Plug-In
pageName=DashboardScreen - Loading...
pageType=
pe=lnk_o
pev2=pageDetail
s=2432x1520
server=1.1 pqalmttws301.ie.google.net:81
t=22/06/2014 10:00:00 2 420
v12=3468337910
v4=0
v9=dat=279333:279364:375870:743798:744035:743802:744033:743805:783950:783797:783949:784088
vid=29E364C5051D2894-400001468000F0EE
变成这样:
_=1406048396605<CONTROL_CHARACTER_HERE>bh=1244<CONTROL_CHARACTER_HERE>bw=1711<CONTROL_CHARACTER_HERE>c=24<CONTROL_CHARACTER_HERE>c19=DashboardScreenc2=2014-07-22T10:00:00-0700.....etc
所以我基本上是将一个多行文件制作成一个单行文件,用 CONTROL_CHARACTER 分隔每个字段。
这是我目前拥有的:
private String putIntoExpectedFormat() {
File f1 = new File("InputFile.txt");
File f2 = new File("OutputFile.txt");
InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f2);
StringBuilder sb = new StringBuilder();
byte[] buf = new byte[1024];
int len;
while( (len=in.read(buf)) > 0) {
out.write(buf,0,len);
}
in.close();
out.close();
}
我什至不确定我这样做是否正确。有人知道怎么做这个吗?
最佳答案
因为它是一个文本文件,所以你必须使用 Reader
读取字符流的类。为了获得更好的性能,请使用 BufferedReader
Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.
您可以使用 Java 7 - The try-with-resources Statement
示例代码:
try (BufferedReader reader = new BufferedReader(new FileReader(
new File("InputFile.txt")));
BufferedWriter writer = new BufferedWriter(new FileWriter(
new File("OutputFile.txt")))) {
String line = null;
while ((line = reader.readLine()) != null) {
writer.write(line);
// write you <CONTROL_CHARACTER_HERE> as well
}
}
关于java - 如何将多行文件变成用控制字符分隔的单行文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24894123/