2

我试图从我的文本文件中删除所有逗号,我哪里出错了?我认为它与 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 + "'");                  
    }
}`
4

5 回答 5

1

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

于 2013-11-12T19:48:07.193 回答
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(",","\\.);
于 2014-08-25T10:44:14.103 回答
0

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

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

于 2013-11-12T19:53:39.593 回答
0
line.replaceAll(",","\\.");

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

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

或直接打印:

System.out.println(line.replaceAll(",","\\."));
于 2013-11-12T19:48:41.620 回答
0

你可以这样尝试:

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

注意 Java 字符串是不可变的

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

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

当你说:

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

那么该行没有变化,它返回一个新的字符串。

于 2013-11-12T19:49:20.260 回答