为什么此代码打印空字符串?

Why is this code printing a null string?

我正在尝试从文本文件中获取一组字符,然后将其存储在一个字符串中并进行打印。但是,当编译 运行 文件时,它 returns 为空。

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

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

您的代码 return 是从文件中读取的最后一行。 你想 return out.toString() 代替。