为什么这段代码打印出一个空字符串?

时间:2015-03-18 19:40:23

标签: java inputstream

我正在尝试从文本文件中获取一组字符,然后将其存储在字符串中并打印出来。但是,在编译并运行该文件时,它将返回null。

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class ReadString
{
    public static void main(String[] args) throws FileNotFoundException, IOException
    {

    ReadString read = new ReadString();
    System.out.println(read.readFileTxt());   //Prints the string content read from input stream

    }   

    public String readFileTxt() throws FileNotFoundException, IOException
    {
    InputStream in = new FileInputStream(new File("test.txt"));
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        StringBuilder out = new StringBuilder();
        String line;
            while ((line = reader.readLine()) != null) 
        {
            out.append(line);
            }

      //  reader.close();
    return line;
    }       
}

2 个答案:

答案 0 :(得分:1)

您将返回最后一行(因为它导致循环退出而返回null)而不是out.toString()

答案 1 :(得分:0)

您的代码返回从文件中读取的最后一行。 你想要返回out.toString()。