BufferedReader: read multiple lines into a single

2019-06-15 14:39发布

I'm reading numbers from a txt file using BufferedReader for analysis. The way I'm going about this now is- reading a line using .readline, splitting this string into an array of strings using .split

public InputFile () {
    fileIn = null;

    //stuff here

    fileIn = new FileReader((filename + ".txt"));
    buffIn = new BufferedReader(fileIn);


    return;
    //stuff here
}

public String ReadBigStringIn() {
    String line = null;

    try { line = buffIn.readLine(); }
    catch(IOException e){};

    return line;
}

public ProcessMain() {
    initComponents();
    String[] stringArray;
    String line;

    try {
        InputFile stringIn = new InputFile();
        line = stringIn.ReadBigStringIn();
        stringArray = line.split("[^0-9.+Ee-]+"); 
        // analysis etc.
    }
}

This works fine, but what if the txt file has multiple lines of text? Is there a way to output a single long string, or perhaps another way of doing it? Maybe use while(buffIn.readline != null) {}? Not sure how to implement this.

Ideas appreciated, thanks.

7条回答
The star\"
2楼-- · 2019-06-15 15:05

This creates a long string, every line is seprateted from string " " (one space):

public String ReadBigStringIn() {
    StringBuffer line = new StringBuffer();


    try { 
        while(buffIn.ready()) {
        line.append(" " + buffIn.readLine());
    } catch(IOException e){
        e.printStackTrace();
    }

    return line.toString();
}
查看更多
登录 后发表回答