2017-06-05 123 views
0

我正在尝试编写该问题的程序:“编写一个程序,该程序将向用户提出一个字符串和一个文件名,然后从该字符串中删除所有出现的字符串文本文件。”替换字符串删除文本中的所有内容

这是我到目前为止有:

import java.io.FileNotFoundException; 
    import java.io.PrintWriter; 
    import java.util.*; 

    public class RemoveText { 
     public static void main(String[] args){ 

    //creates a scanner to read the user's file name 
    Scanner input = new Scanner(System.in); 
    System.out.println("Enter a file name: "); 
    String fileName = input.nextLine(); 

    java.io.File file = new java.io.File(fileName); 
    java.io.File newFile = new java.io.File(fileName); 
    Scanner stringToRemove = new Scanner(System.in); 
    System.out.println("Enter a string you wish to remove: "); 
    String s1 = stringToRemove.nextLine(); 

    //creating input and output files 
    try { 
     Scanner inputFile = new Scanner(file); 
     //reads data from a file 
     while(inputFile.hasNext()) { 
      s1 += inputFile.nextLine(); 
     } 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } 

    //supposed to replace each instance of the user input string 
    //but instead deletes everything on the file and i don't know why 
    String s2 = s1.replaceAll(s1, ""); 

    try { 
     PrintWriter output = new PrintWriter(newFile); 
     output.write(s2); 
     output.close(); 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } 

    //closing various scanners 
    input.close(); 
    stringToRemove.close(); 
    } 
} 

但由于某些原因,而不是用空格替换字符串,整个文本文件变空。我究竟做错了什么?

编辑:好的,我采纳了大家的建议,并设法通过引入第三个字符串变量并使用更多描述性变量名来解决变量问题。

Scanner s1 = new Scanner(System.in); 
    String stringToRemove = s1.nextLine(); 
    String fileContents = null; 

    try { 
    //stuff here 
     while (inputFile.hasNextLine()) { 
     fileContents += inputFile.nextLine(); 
    } catch { //more stuff } 

    String outputContent = fileContents.replaceAll(stringToRemove, ""); 

我现在的问题是,新文件的开头中继新内容之前,“零”开始。

+2

因为你保存文本和字符串删除在同一个变量? (然后做:'s1.replaceAll(s1,“”)') – alfasin

+1

为你的变量选择好的名字。使用'stringToRemove'作为第一个's1'(并且将当前的'stringToRemove'重命名为'input'或类似的名称),并且使用'fileContents'而不是's1'的第二次使用,将会奇迹般地解释为什么'fileContents .replaceAll(stringToRemove,“”)'是正确的,'stringToRemove.replaceAll(stringToRemove,“”)'返回一个空字符串 – tucuxi

回答

3
String s2 = s1.replaceAll(s1, ""); 

的replaceAll方法的第一个参数是你在找什么来代替,而你正在寻找S1,你说这个代码清理所有S1的内容...

1

你在哪里错了是您将文件内容附加到s1,这是您要删除的字符串。 尝试引入s3然后做

s2 = s3.replaceAll(s1,“”);

+1

顺便说一句,将整个内容读入内存是低效的。如果文件内容很长,您的程序将耗尽内存。 –