解析字符串文本的每一行

时间:2013-12-10 12:49:10

标签: java parsing

我有一个Logfile(log.txt),我需要在每个字符串之间放置一个逗号(只要有空白)。必须为日志文件的每一行/每行完成此操作。要解析我尝试使用Stringbuilder的文本(可能是错误的)并且实际代码没有任何效果(可能是因为System printline在while块内)。帮助赞赏!这就是Logfile的应用。每当有空白时基本上放置一个逗号。

输入 "Hello" this is 1 sentence blablabla

输出 "Hello" , this , is , 1 , sentence , blablabla

更新已解决!

public class changeFile {
public static void main(String[] args) throws IOException{

File f=new File("C:/downloads/log.txt");
FileReader in = new FileReader(f);
BufferedReader br = new BufferedReader(in);
String line;
StringBuilder builder = new StringBuilder();
String delim = "";

try { 
while ((line = br.readLine()) != null) {
delim =",";
builder.append(delim).append(line);
System.out.println(line);
}               
}catch (IOException e) {
e.printStackTrace();
}
br.close();
in.close();
}
}

3 个答案:

答案 0 :(得分:1)

尝试使用您自己代码的此修改版本。

然后你可以稍微改一下(添加几行)来删除旧文件, 并将新文件重命名为旧名称,如果这是您想要的。

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;

public class Test {

public static void main(String[] args) throws Exception {

    File f=new File("C:/downloads/log.txt");
    FileReader in = new FileReader(f);
    BufferedReader br = new BufferedReader(in);
    String line;
    StringBuilder builder = new StringBuilder();
    String delim = "";

    while ((line = br.readLine()) != null) {
        delim =",";
        builder.append(line);
        builder.append(delim);
        builder.append(System.getProperty("line.separator"));
    }

    br.close();

    BufferedWriter bw = new BufferedWriter
                        (new FileWriter("C:/downloads/log_modified.txt"));
    bw.write(builder.toString());
    bw.close();

}

}

答案 1 :(得分:0)

您需要将该代码放在main()方法中。例如:

public class ChangeFile {
    public static void main(String[] args) throws IOException {
        File f = new File("C:/downloads/log.txt");
        FileReader in = new FileReader(f);
        BufferedReader br = new BufferedReader(in);
        String line;
        StringBuilder builder = new StringBuilder();
        String delim = ",";

        while ((line = br.readLine()) != null) {
            builder.append(delim).append(line);

        }
        System.out.println(builder);
        br.close();
        in.close();
    }
}

答案 2 :(得分:0)

代码不起作用,因为没有方法:既不是main()也不是其他任何东西。将代码放在main()中。同时使用一组输入给出预期输出。