![](/img/trans.png)
[英]How to add the first number of every row in a txt file to an array in Java
[英]Read and add the first number of TXT file in java
那么如何将 +1 添加到 java 中的 TXT 文件的第一个数字
例如我的 TXT 是这样的
3
Text
Text
Text
在下添加更多文本很容易,但我不确定如何添加 1 到 3 等等
4
Text
Text
Text
Text
如果您的文件很小,则读取整个内容,然后编辑,然后以写入模式覆盖它:
List<String> lines = Files.readAllLines(Paths.get("e:\\data.txt"));
int num = Integer.parseInt(lines.get(0));
lines.set(0, Integer.toString(++num));
//by default opens file in overwrite mode
FileWriter fw = new FileWriter("e:\\data.txt");
PrintWriter pw = new PrintWriter(fw);
for(String line : lines) {
pw.println(line);
}
pw.close();
对于大文件,您可以像这样使用 RandomeAccessFile class :文件内容:
0001
Text
Text
然后使用以下代码:
RandomAccessFile raf = new RandomAccessFile("e:\\data.txt", "rw");
int num = Integer.parseInt(raf.readLine());
num+=99;
raf.seek(0);
raf.writeBytes(String.format("%04d", num));
raf.close();
文件将包含以下内容:
0100
Text
Text
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.