2015-05-15 39 views
0

我有一个txt文件,我想要做的是打开它并删除所有多个空格,以便它们只成为一个。我使用:Java - 打开txt文件并清除所有多个空格

br = new BufferedReader(new FileReader("C:\\Users\\Chris\\Desktop\\file_two.txt")); 
bw = new BufferedWriter(new FileWriter("C:\\Users\\Chris\\Desktop\\file_two.txt")); 

while ((current_line = br.readLine()) != null) { 
    //System.out.println("Here."); 
    current_line = current_line.replaceAll("\\s+", " "); 
    bw.write(current_line); 
}   
br.close(); 
bw.close(); 

但是,至少据我看来正确的是,没有什么东西写在文件上。如果我使用system.out.println命令,它不会被打印,这意味着执行永远不会在while循环中......我做错了什么?由于

+0

你的代码工作我使用stringreaders和作家,而不是文件,所以循环和密切的罚款。 –

回答

4

您正在阅读的文件,并在同一时间写在it..it内容是不允许的......

所以最好先阅读文件和处理的文本存放在另一个文件中,最后的方式替换为新one..try原始文件这个

 br = new BufferedReader(new FileReader("C:\\Users\\Chris\\Desktop\\file_two.txt")); 
     bw = new BufferedWriter(new FileWriter("C:\\Users\\Chris\\Desktop\\file_two_copy.txt")); 
     String current_line; 
     while ((current_line = br.readLine()) != null) { 
      //System.out.println("Here."); 
      current_line = current_line.replaceAll("\\s+", " "); 
      bw.write(current_line); 
      bw.newLine(); 
     } 
     br.close(); 
     bw.close(); 
     File copyFile = new File("C:\\Users\\Chris\\Desktop\\file_two_copy.txt"); 
     File originalFile = new File("C:\\Users\\Chris\\Desktop\\file_two.txt"); 
     originalFile.delete(); 
     copyFile.renameTo(originalFile); 

它可以帮助...

1

您必须先读,然后写,你不能读取和写入到在同一个文件同时,您需要使用RandomAccessFile来做到这一点。

如果你不想学习新的技术,你要么需要编写一个单独的文件,或缓存所有的行存储(即ArrayList),但你初始化你BufferedWriter之前,你必须关闭BufferedReader,否则会得到文件访问错误。

编辑: 如果你想研究它,这里是一个RandomAccessFile用例的例子,用于你的预期用途。值得指出的是,如果最后一行的长度小于或等于原始长度,这种方法才有效,因为这种技术基本上覆盖了现有的文本,但应该非常快,只需很少的内存开销,并且可以处理非常大的文件:

public static void readWrite(File file) throws IOException{ 
    RandomAccessFile raf = new RandomAccessFile(file, "rw"); 

    String newLine = System.getProperty("line.separator"); 

    String line = null; 
    int write_pos = 0; 
    while((line = raf.readLine()) != null){ 
     line = line.replaceAll("\\s+", " ") + newLine; 
     byte[] bytes = line.getBytes(); 
     long read_pos = raf.getFilePointer(); 
     raf.seek(write_pos); 
     raf.write(bytes, 0, bytes.length); 
     write_pos += bytes.length; 
     raf.seek(read_pos); 
    } 
    raf.setLength(write_pos); 
    raf.close(); 
} 
1

有几个问题你的方法:

  • 主要原因之一是,你正试图读取并同时写入同一个文件。
  • 其他是new FileWriter(..)总是会创建新的空文件,防止FileReader从您的文件中读取任何东西。

您应该阅读file1的内容并将其修改后的版本写入file2。之后用file2代替file1

您的代码可以看看或多或少像

Path input = Paths.get("input.txt"); 
Path output = Paths.get("output.txt"); 

List<String> lines = Files.readAllLines(input); 
lines.replaceAll(line -> line.replaceAll("\\s+", " ")); 

Files.write(output, lines); 
Files.move(output, input, StandardCopyOption.REPLACE_EXISTING); 
相关问题