格式化字符串以获取列中的单词

时间:2016-12-23 18:29:59

标签: java string-formatting file-writing

我有一个文字:

c:\MyMP3s\4 Non Blondes\Bigger!\Faster, More!_Train.mp3

我想从这些文字中删除这些字符::,\!._ 并格式化文本,然后像这样:

c
MyMP3s
4
Non
Blindes
Bigger
Faster
More
Train
mp3

并将所有这些写入文件中。 这是我做的:

public static void formatText() throws IOException{

    Writer writer = null;
    BufferedReader br = new BufferedReader(new FileReader(new File("File.txt")));

    String line = "";
    while(br.readLine()!=null){
        System.out.println("Into the loop");

        line = br.readLine();
        line = line.replaceAll(":", " ");
        line = line.replaceAll(".", " ");
        line = line.replaceAll("_", " ");

        line = System.lineSeparator();
        System.out.println(line);
        writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("Write.txt")));
        writer.write(line);
    }

它不起作用!

例外:

 Into the loop
Exception in thread "main" java.lang.NullPointerException
    at Application.formatText(Application.java:25)
    at Application.main(Application.java:41)

1 个答案:

答案 0 :(得分:1)

在代码的最后,您有:

line = System.lineSeperator()

这会重置你的替换品。另一件需要注意的事情是String#replaceAll接受第一个参数的正则表达式。所以你必须转义任何序列,例如.

String line = "c:\\MyMP3s\\4 Non Blondes\\Bigger!\\Faster, More!_Train.mp3";
System.out.println("Into the loop");

line = line.replaceAll(":\\\\", " ");
line = line.replaceAll("\\.", " ");
line = line.replaceAll("_", " ");
line = line.replaceAll("\\\\", " ");

line = line.replaceAll(" ", System.lineSeparator());

System.out.println(line);

输出结果为:

Into the loop
c
MyMP3s
4
Non
Blondes
Bigger!
Faster,
More!
Train
mp3