[英]Why is this code printing a null string?
I am trying to take a set of characters from a text file then store it in a string and print it. 我正在尝试从文本文件中提取一组字符,然后将其存储在字符串中并进行打印。 However when compile and run the file, it returns null.
但是,编译并运行文件时,它返回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;
}
}
您返回的是最后一行(该行为null,因为它导致循环退出),而不是out.toString()
。
Your code returns the last line read from the file. 您的代码返回从文件读取的最后一行。 You want to return out.toString() instead.
您想返回out.toString()。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.