所以我想做的是这样的:假设我有一个链接到系统中物理文件的File对象。我想在将内容写回新文件之前对其进行几次修改。我怎样才能做到这一点?这是示例代码:
File x = new File("somefile.txt");
// Ask user to enter a String
Scanner s = new Scanner(x);
while(s.hasNextLine())
String nextLine = s.nextLine();
if(userString.equals(nextLine))
nextLine = nextLine.toUpperCase();
现在,我不想修改文件 x 本身。我也不想写物理文件。我只想以相同的顺序表示同一个文件,但有些行是大写的,这样我就可以再次循环访问相同的行。
我想要做的是我希望能够再次循环访问相同(但已修改)的文件。
我该怎么做?
最佳答案
您可以将每一行存储在 ArrayList<String>
中当您读入它们时,然后在写出内容之前根据需要多次迭代列表。
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
public class Fm {
public static void main(String[] args) throws Exception {
File x = new File("somefile.txt");
ArrayList<String> fileLines = new ArrayList<String>();
String userString = "bar";
Scanner s = new Scanner(x);
while(s.hasNextLine()) {
String nextLine = s.nextLine();
if(userString.equals(nextLine))
nextLine = nextLine.toUpperCase();
fileLines.add(nextLine);
}
for (String line : fileLines) {
System.out.println("Do something with: " + line);
}
}
}
$ cat somefile.txt
foo
bar
baz
$ java Fm
Do something with: foo
Do something with: BAR
Do something with: baz
关于java - 我应该如何在Java中暂时表示内存中的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28981991/