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

Formatting string to get just words in a column

我有一条短信:

c:\MyMP3s 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)

在您的代码末尾,您有:

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