2016-10-25 116 views
3

如何替换对于字符串太大的文件中的文本?我一直在使用以下内容来替换我见过的大部分文件中的文本:如何替换字符串文件太大的文本

File f = new File("test.xml"); 
String content = FileUtils.readFileToString(f, "UTF-8"); 

content = content.replaceFirst("some text", "new text"); 
FileUtils.writeStringToFile(f, content, "UTF-8"); 

这适用于正常大小的文件。但是,我收到的一些文件非常大(太大而无法存储在字符串中),并导致溢出。我该如何替换这些文件中的文字?

+0

有多大文件 ?? – Biswajit

+4

您可以尝试使用缓冲的'Reader','Writer'并在写回到另一个文件时在每行中进行替换。 – Mena

+0

在大多数情况下,BufferedReader和BufferedWriter是读取/写入Java文件的方式。 –

回答

1
try { 
      File f=new File("test.xml"); 
      BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(f))); 
      String content=null; 

      while((content=reader.readLine())!=null) 
      { 
       content = content.replaceFirst("some text", "new text"); 
       System.out.println(content); 
      } 

     } catch (Exception e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
1

尝试使用一个FileInputStream读它行明智

FileInputStream fs = new FileInputStream("test.xml"); 
BufferedReader reader = new BufferedReader(new InputStreamReader(fs)); 

很抱歉,如果有在代码中的任何错误,我不能尝试的代码我现在

+0

while((line = reader.readLine() )!= null){/ * do stuff * /} – reden

+0

替换为while并将其写入新生成的文件中:) – DLIK

1

可以使用sed命令来替换大文件的串像下面[Linux的]

String[] cmdarr = {"bash", "-c", "sed 's/oldstring/newstring/g' input.txt > output.txt"}; 
Process runCmd = Runtime.getRuntime().exec(cmdarr); 

在Windows中,您可以安装SED,使用一些东西一样

String[] cmdarr = {"cmd", "/c", "sed 's/oldstring/newstring/g' input.txt > output.txt"}; 
Process runCmd = Runtime.getRuntime().exec(cmdarr); 

更多Link

+0

我尝试在命令行上运行“cmdarr”的最后一个元素,并且它的运行速度非常快。 –

0

尝试使用FART的Windows(查找和替换文本) :fart -c big_filename.txt "find_this_text" "replace_to_this"