从文本文件中删除逗号

时间:2013-11-12 19:45:39

标签: java

我试图从我的文本文件中删除所有逗号,我哪里错了?我认为它与replaceAll字段有关,我已经对它进行了研究,但找不到任何答案。我还需要在“;”后面有一个新的行。以及删除逗号。提前谢谢

`public static void open(){
     // The name of the file to open.
    String fileName = "Test.txt";
    // This will reference one line at a time
    String line = null;

    try {
        // FileReader reads text files in the default encoding.
        FileReader fileReader = new FileReader(fileName);

        // Always wrap FileReader in BufferedReader.
        BufferedReader bufferedReader = new BufferedReader(fileReader);

        while((line = bufferedReader.readLine()) != null) {
            line.replaceAll(",","\\.");

            System.out.println(line);
        }   
        // Always close files.
        bufferedReader.close();         
    }
    catch(FileNotFoundException ex) {
        System.out.println(
            "Unable to open file '" + 
            fileName + "'");                
    }
    catch(IOException ex) {
        System.out.println(
            "Error reading file '" 
            + fileName + "'");                  
    }
}`

5 个答案:

答案 0 :(得分:1)

字符串在Java中是不可变的,因此System.out.println(line.replaceAll(",","\\."))就是您想要的。您想要打印返回的值。

答案 1 :(得分:0)

line.replaceAll(",","\\.");

Java字符串是不可变的 - 这样做改变line但返回一个新的String,并应用了所需的替换。请尝试将其分配给变量:

String s = line.replaceAll(",","\\.");

或直接打印:

System.out.println(line.replaceAll(",","\\."));

答案 2 :(得分:0)

您可以尝试这样:

String s = line.replaceAll(",","\\.");

注意Java字符串是不可变的

或者您可以选择直接将其打印为:

System.out.println(line.replaceAll(",","\\."));

在你的代码中说:

line.replaceAll(",","\\.");

然后该行没有变化,它返回一个新的String。

答案 3 :(得分:0)

line.replaceAll(",","\\.");更改为line = line.replaceAll(",","\\.");可以解决您的问题。

至于在“;”之后添加换行符使用line = line.replaceAll(";",";\n");

答案 4 :(得分:0)

尝试使用以下命令加载文件:

public static String readAllText(String filename) throws Exception {
    StringBuilder sb = new StringBuilder();
    Files.lines(Paths.get(filename)).forEach(sb::append);
    return sb.toString();
}

然后改变你想要的东西。

String file = readAllText("myfile.txt");
file = file.replace(",","\\.);