【发布时间】:2018-06-16 02:24:37
【问题描述】:
我有一些唯一的 ID,必须附加到每行的末尾。我不想创建另一个文件,我想在同一个文件中执行此操作,该文件用于逐行读取并基于该行生成唯一 ID。
我使用 java 进行此操作,这是我的代码,
String filename="location.txt";
Path pathToFile = Paths.get(filename);
FileWriter fstream = null;
BufferedWriter bw=null;
PrintWriter pw=null;
try {
fstream = new FileWriter(filename, true);
bw=new BufferedWriter(fstream);
pw=new PrintWriter(bw);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try (BufferedReader br = Files.newBufferedReader(pathToFile, StandardCharsets.US_ASCII)) {
// read the first line from the text file
String line = br.readLine();
// loop until all lines are read
while (line!=null) {
// use string.split to load a string array with the values from
// each line of
// the file, using a " " as the delimiter
String[] attributes = line.split(" ");
System.out.print("Sensor["+attributes[0]+"] : ");
double x=Double.parseDouble(attributes[1]);
double y=Double.parseDouble(attributes[2]);
GeoHash geoCode=GeoHash.withCharacterPrecision(x, y, 10);
System.out.print(geoCode+"\n");
pw.println(line+" "+geoCode);
line = br.readLine();
}
br.close();
pw.close();
bw.close();
fstream.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
System.out.println("Generated!!");
}
目前通过运行此代码,我将在我的文件末尾获得附加行作为新行,如下所示: 输出:
1 21.5 23
2 24.5 20
3 19.5 19
4 22.5 15
5 24.5 121 21.5 23 seb673undf
2 24.5 20 skq5rh5dcg
3 19.5 19 s7mwbmg7sp
4 22.5 15 sk48j248j2
5 24.5 12 sk2e3h44u7
有没有办法解决这个问题?或者其他任何简单的方法来做到这一点?
【问题讨论】:
-
不是答案,但您不需要关闭缓冲阅读器,因为您正在使用 try-with。
-
我认为如果不创建新文件就无法做到这一点。文本文件是一个字节数组,两行之间有一个
\n或两个\r\n。如果你想在某一行附加一些东西,你是在\n之前插入一些东西,所以你必须在\n(包括\n)之后移动一些字节之后的所有字节。
标签: java bufferedreader filereader filewriter bufferedwriter