BufferedReader:将多行读入单个字符串 [英] BufferedReader: read multiple lines into a single string

查看:586
本文介绍了BufferedReader:将多行读入单个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用BufferedReader从txt文件读取数字以进行分析。我现在要解决的方法是-使用.readline读取一行,使用.split将字符串拆分为字符串数组

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.
    }
}

很好,但是如果txt文件包含多行文本怎么办?是否有一种输出单个长字符串的方法,或者还有另一种方式来输出呢?也许使用 while(buffIn.readline!= null){} ?不确定如何实现。

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.

推荐答案

是的,这里需要一个循环。

You are right, a loop would be needed here.

通常的习惯用法(仅使用纯Java)是这样的:

The usual idiom (using only plain Java) is something like this:

public String ReadBigStringIn(BufferedReader buffIn) throws IOException {
    StringBuilder everything = new StringBuilder();
    String line;
    while( (line = buffIn.readLine()) != null) {
       everything.append(line);
    }
    return everything.toString();
}

这会删除换行符-如果要保留换行符,请不要使用 readLine()方法,但是只需读入 char [] (并将其附加到StringBuilder中)

This removes the line breaks - if you want to retain them, don't use the readLine() method, but simply read into a char[] instead (and append this to your StringBuilder).

请注意,此循环将一直运行到流结束(如果未结束则将阻塞),因此如果您需要其他条件来完成循环,在其中实施。

Please note that this loop will run until the stream ends (and will block if it doesn't end), so if you need a different condition to finish the loop, implement it in there.

这篇关于BufferedReader:将多行读入单个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆