Java 文件未被更改

Java 文件未被更改,java,file,file-writing,Java,File,File Writing,我正在编写一个程序,将任何特殊字符更改为文件中的空格,然后重新读取该文件,并获得字长的频率。运行时,它似乎运行正常,但当我打开文件时,没有任何更改 File tempFile = File.createTempFile("buffer", ".tmp"); fw = new FileWriter(tempFile); reader = new BufferedReader(new FileReader(file)); System.out.println("File opened"); Str

我正在编写一个程序,将任何特殊字符更改为文件中的空格,然后重新读取该文件,并获得字长的频率。运行时,它似乎运行正常,但当我打开文件时,没有任何更改

File tempFile = File.createTempFile("buffer", ".tmp");
fw = new FileWriter(tempFile);
reader = new BufferedReader(new FileReader(file));
System.out.println("File opened");

String line = reader.readLine();

// Replace non-alphanumeric symbols with spaces
System.out.println("Replacing non-alphanumeric symbols\n");
while(line != null) {
   line = line.replaceAll("a-zA-Z0-9_-", " ");
   fw.write(line);
   line = reader.readLine();                
   }
System.out.println("Lines replaced");
file = tempFile;
reader.close();

文件已初始化到此代码段上方。

您的代码中有问题

line.replaceAll()
是一个函数,返回一个带有替换字符的新
String
对象。 您的代码将替换给定的行,但不会将结果分配给任何变量

它应该看起来像这样:

File tempFile = File.createTempFile("buffer", ".tmp");
fw = new FileWriter(tempFile);
reader = new BufferedReader(new FileReader(file));
System.out.println("File opened");

String line = reader.readLine();

// Replace non-alphanumeric symbols with spaces
System.out.println("Replacing non-alphanumeric symbols\n");
while(line != null) {
   line = line.replaceAll("a-zA-Z0-9_-", " "); //assign the replaced value to the variable
   fw.write(line);
   line = reader.readLine();                
   }
System.out.println("Lines replaced");
file = tempFile;
reader.close();

你的代码有问题

line.replaceAll()
是一个函数,返回一个带有替换字符的新
String
对象。 您的代码将替换给定的行,但不会将结果分配给任何变量

它应该看起来像这样:

File tempFile = File.createTempFile("buffer", ".tmp");
fw = new FileWriter(tempFile);
reader = new BufferedReader(new FileReader(file));
System.out.println("File opened");

String line = reader.readLine();

// Replace non-alphanumeric symbols with spaces
System.out.println("Replacing non-alphanumeric symbols\n");
while(line != null) {
   line = line.replaceAll("a-zA-Z0-9_-", " "); //assign the replaced value to the variable
   fw.write(line);
   line = reader.readLine();                
   }
System.out.println("Lines replaced");
file = tempFile;
reader.close();

你怎么看
file=tempFile真的有吗?您是否调试过它以查看
行.replaceAll(“a-zA-Z0-9_-”,“”)上发生的情况?请阅读有关调试代码的提示。@Arminius我从您的评论中猜测,它不是我所认为的那样。我认为它覆盖了原始文件。@ndsmith它只使
文件
变量指向您写入的临时文件。您的原始文件未被触动。您认为
file=tempFile真的有吗?您是否调试过它以查看
行.replaceAll(“a-zA-Z0-9_-”,“”)上发生的情况?请阅读有关调试代码的提示。@Arminius我从您的评论中猜测,它不是我所认为的那样。我认为它覆盖了原始文件。@ndsmith它只使
文件
变量指向您写入的临时文件。您的原始文件未被触动。感谢您捕捉到这一点,但它仍然没有修复它。我在代码和问题中都修复了它。再次感谢你。谢谢你抓住了它,但它仍然没有解决它。我在代码和问题中都解决了它。再次感谢你。