Reputation: 1683
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.
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;
}
}
Upvotes: 0
Views: 83
Reputation: 871
Your code returns the last line read from the file. You want to return out.toString() instead.
Upvotes: 0
Reputation: 2662
You're returning the last line (which is null because it caused the loop to exit) instead of out.toString()
.
Upvotes: 1