如何实现具有最大字符数的BufferedReader readLine方法?

时间:2014-08-06 12:21:24

标签: java bufferedreader

我需要一个BufferedReader方法,该方法可以在换行符处停止,也可以在达到读取的最大字符数时停止。

String readLine(int maxCharacters) throws IOException;

实现此功能的最佳方法是什么?

此方法的原因是为了防止OutOfMemoryError例外,例如:

Exception in thread "Thread-3647" java.lang.OutOfMemoryError: Java heap space
        at java.util.Arrays.copyOf(Arrays.java:2367)
        at java.lang.AbstractStringBuilder.expandCapacity(AbstractStringBuilder.java:130)
        at java.lang.AbstractStringBuilder.ensureCapacityInternal(AbstractStringBuilder.java:114)
        at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:535)
        at java.lang.StringBuffer.append(StringBuffer.java:322)
        at java.io.BufferedReader.readLine(BufferedReader.java:363)
        at java.io.BufferedReader.readLine(BufferedReader.java:382)

2 个答案:

答案 0 :(得分:0)

制作BufferedReader的本地副本,并在bufferLoop方法的readLine(boolean ignoreLF)底部添加如下内容:

if (s.length() > MAX_CHARACTERS) {
    throw new IOException("Next line is longer than " + MAX_CHARACTERS
            + " characters.");
}

答案 1 :(得分:-2)

使用read(char[] buf)方法,并将char数组的大小设置为最大值;

public class Main {

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


    String path = "asdf.txt";

    BufferedWriter write = null;
    try {
        write = new BufferedWriter(new FileWriter(path));
        write.write("This is a Test");

        write.flush();

    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    write.close();


    try {
        FileReader read = new FileReader(path);
        BufferedReader re = new BufferedReader(read);


        char[] ar = new char[8];

        re.read(ar);

        re.close();
        read.close();

        System.out.println(new String(ar));

        //System.out.println(r);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }



}

}