If I have something like this in my code:
String line = r.readLine(); //Where r is a bufferedReader
How can I avoid a crash if the next line is the end of the file? (i.e. null)
I need to read the next line because there may be something there that I need to deal with but if there isn't the code just crashes.
If there is something there then all is OK, but I can't be guaranteed that there will be something there.
So if I do something like: (pseudo code):
if (r.readLine is null)
//End code
else {check line again and excecute code depending on what the next line is}
The issue I have with something like this is, that when I check the line against null, it already moves onto the next line, so how can I check it again?
I've not worked out a way to do this - any suggestions would be a great help.
Am... You can simply use such a construction:
String line;
while ((line = r.readLine()) != null) {
// do your stuff...
}
If you want loop through all lines use that:
while((line=br.readLine())!=null){
System.out.println(line);
}
br.close();
You can use the following to check for the end of file.
public bool isEOF(BufferedReader br)
{
boolean result;
try
{
result = br.ready();
}
catch (IOException e)
{
System.err.println(e);
}
return result;
}
In your case you can read the next line because there may be something there.If there isn't anything, your code won't crash.
String line = r.readLine();
while(line!=null){
System.out.println(line);
line = r.readLine();
}
A question in the first place, why don't you use "Functional Programming Approach"? Anyways, A new method lines() has been added since Java 1.8, it lets BufferedReader returns content as Stream. It gets all the lines from the file as a stream, then you can sort the string based on your logic and then collect the same in a list/set and write to the output file. If you use the same approach, there is no need to get worried about NullPointerException. Below is the code snippet for the same:-
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Collectors;
public class LineOperation {
public static void main(String[] args) throws IOException {
Files.newBufferedReader(Paths.get("C://xyz.txt")).
lines().
collect(Collectors.toSet()). // You can also use list or any other Collection
forEach(System.out::println);
}
}
You can do it via BufferReader. I know this is not relevant to following question. But I would post it for extra fact for a newbie who would not use BufferReader but Scanner for reading file.
A part from BufferReader you could use Java Scanner class to read the file and check the last line.
Buffer Reader
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
// process the line
}
}
Scanner
try {
Scanner scanner = new Scanner(new FileReader(file));
while (scanner.hasNext()) {
// Above checks whether it has or not ....
}
} catch (IOException e) {
e.printStackTrace();
}
If you use this code fragment in a multi threaded environment, go ahead with BufferReader since its synchronized.
In addition, BufferReader is faster than Scanner.
If you would like to do some check like:
if (reader.ready())
stringBuilder.append("#");
You can use ready()
public static void check() throws IOException {
InputStream in = new FileInputStream(new File(filePath));
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
if (reader.ready())
stringBuilder.append("#");
}
String returnedString = stringBuilder.toString();
System.out.println(returnedString);
}
You could purposely have it throw the error inside your loop. i.e.:
String s = "";
while (true) {
try {
s = r.readline();
}catch(NullPointerException e) {
r.close();
break;
}
//Do stuff with line
}
what everyone else has sad should also work.
Related
I read two files from different paths and while reading unable to write second file contents inside while loop, it is forcing me to initialize the variable which rt in below program. Please help me how to fix it to get
expected output. Thanks in advance..!!
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class ReadingFiles
{
public static void main(String[] args) throws IOException
{
String inp = "location\\first.txt";
String two = "location\\second.txt";
BufferedReader br = new BufferedReader(new FileReader(inp));
BufferedReader br2 = new BufferedReader(new FileReader(two));
String st,rt;
BufferedWriter bw = new BufferedWriter(new FileWriter("location"));
while((st=br.readLine())!= null || (rt=br2.readLine())!= null )
{
bw.write(st);
bw.newLine();
/*bw.write(rt);
bw.newLine();
System.out.println(rt);*/
//instance variable rt of type String is forcing me to initialize like
//for local variable and throwing nullpointer exception instead of fetching
//second file contents
}
bw.close();
}
}
Please find my program above, i am trying to write two text files contents
into third file. And the sample input and output given below
input
in file-1 a1a1a1
b2b2b2
c3c3c3
in file-2 d1d1d1
e2e2e2
f3f3f3
output
a1a1a1
d1d1d1
b2b2b2
e2e2e2
c3c3c3
f3f3f3
There is several mistakes you have done in the code and also there are better ways to implement the code.
But for your understatement i will update your existing code.
1) st and rt should be initialized. because when first time st is initializing rt is not yet initialized.
2) || should be &&. because you need to loop until all the files are finished reading.
3) st & rt should be checked if it's null or not.
please check following code .
public class ReadingFiles
{
public static void main(String[] args) throws IOException
{
String inp = "first.txt";
String two = "second.txt";
BufferedReader br = new BufferedReader(new FileReader(inp));
BufferedReader br2 = new BufferedReader(new FileReader(two));
String st,rt="";
BufferedWriter bw = new BufferedWriter(new FileWriter("location"));
boolean isCompleted = false;
while( !isCompleted)
{
st=br.readLine() ;
bw.write(st==null?"":st);
bw.newLine();
rt=br2.readLine();
bw.write(rt==null?"":rt);
bw.newLine();
isCompleted = (st==null && rt == null) ? true : false ;
}
bw.close();
}
}
I would do this with an infinite do while loop instead of while and manage the loop exit condition in a seperate if inside my loop.
Why? Because the second conditional statement in your while header may not be executed since it is an or (||) and the compiler ignores the rest of your conditional statement when the first statement istrue and therefore rtnever get initiated. Thats why the compiler is forcing you to initialize rt.
You aren't closing your readers, and I would prefer the try-with-resources over explicit closes. Then, read each line from your respective files in an infinite loop. Test for null from each file individually before writing to the output buffer, and again at the end to terminate your loop when you have exhausted both inputs. Something like,
try (BufferedReader br = new BufferedReader(new FileReader(inp));
BufferedReader br2 = new BufferedReader(new FileReader(two));
BufferedWriter bw = new BufferedWriter(new FileWriter("location"))) {
while (true) {
String st = br.readLine();
if (st != null) {
bw.write(st);
bw.newLine();
}
String rt = br2.readLine();
if (rt != null) {
bw.write(rt);
bw.newLine();
}
if (st == null && rt == null) {
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
Problem: I can't parse my file test.txt, by spaces. I can 1) read text files, and I can 2) parse strings, but I cannot connect the two and parse a text file! My purpose is to learn how to analyze text files. This is a simplified approach to that.
Progress: Thus far, I can read test.txt using FileReader and BufferedReader, and print it to console. Further, I can parse simple String variables. The individual operations run, but I'm struggling with parsing an actual text file. I believe this is because my test.txt is stored in the buffer, and after I .close() it, I can't print it.
Text File Content:
This is a
text file created, only
for testing purposes.
Code:
import java.io.*;
public class ReadFile {
//create method to split text file, call this from main
public void splitIt(String toTest)
{
String[] result = toTest.split(" ");
for (String piece:result)
{
//loop through the array and print each piece
System.out.print(piece);
}
}
public static void main(String[] args) {
//create readfile method
try
{
File test = new File("C:\\final\\test.txt");
FileReader fileReader = new FileReader(test);
BufferedReader reader = new BufferedReader(fileReader);
String line = null;
//While there are still lines to be read, read and print them
while((line = reader.readLine()) != null)
{
System.out.println(line);
splitIt(line);
}
reader.close();
}
//Catch those errors!
catch (Exception ex)
{
ex.printStackTrace();
}
// readFileMethod a = new readFileMethod(line);
System.out.println(a.splitIt());
}
}
Preemptive thank you for your sharing your knowledge. Many posts on reading and parsing have been solved here on SO, but I've not the understanding to implement others' solutions. Please excuse me, I've only been learning Java a few months and still struggle with the basics.
Ok lets make the splitting into a mthod
private static void splitIt (String toTest) {
String[] result = toTest.split(" ");
for (String piece:result)
{
//loop through the array and print each piece.
System.out.println(piece);
}
}
then you can call it from within
while((line = reader.readLine()) != null)
{
System.out.println(line);
splitIt (line);
}
Building on Scary Wombat and your code, i made some changes.
It should now print the Line that is being read in and each word that is separated by space.
import java.io.*;
public class ReadFile {
//create method to split text file, call this from main
public static void splitIt(String toTest)
{
String[] result = toTest.split(" ");
for (String piece:result)
{
//loop through the array and print each piece
System.out.println(piece);
}
}
public static void main(String[] args) {
//create readfile method
try
{
File test = new File("C:\\final\\test.txt");
FileReader fileReader = new FileReader(test);
BufferedReader reader = new BufferedReader(fileReader);
String line = null;
//While there are still lines to be read, read and print them
while((line = reader.readLine()) != null)
{
System.out.println(line); // print the current line
splitIt(line);
}
reader.close();
}
//Catch those errors!
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
I know how to read in lines with Scanner, but how do I use a BufferedReader? I want to be able to read lines into an array. I am able to use the hasNext() function with a Scanner but not a BufferedReader, that is the only thing I don't know how to do. How do I check when the end of the file text has been reached?
BufferedReader reader = new BufferedReader(new FileReader("weblog.txt"));
String[] fileRead = new String[2990];
int count = 0;
while (fileRead[count] != null) {
fileRead[count] = reader.readLine();
count++;
}
readLine() returns null after reaching EOF.
Just
do {
fileRead[count] = reader.readLine();
count++;
} while (fileRead[count-1]) != null);
Of course this piece of code is not the recommended way of reading the file, but shows how it might be done if you want to do it exactly the way you attempted to ( some predefined size array, counter etc. )
The documentation states that readLine() returns null if the end of the stream is reached.
The usual idiom is to update the variable that holds the current line in the while condition and check if it's not null:
String currentLine;
while((currentLine = reader.readLine()) != null) {
//do something with line
}
As an aside, you might not know in advance the number of lines you will read, so I suggest you use a list instead of an array.
If you plan to read all the file's content, you can use Files.readAllLines instead:
//or whatever the file is encoded with
List<String> list = Files.readAllLines(Paths.get("weblog.txt"), StandardCharsets.UTF_8);
using readLine(), try-with-resources and Vector
try (BufferedReader bufferedReader = new BufferedReader(new FileReader("C:\\weblog.txt")))
{
String line;
Vector<String> fileRead = new Vector<String>();
while ((line = bufferedReader.readLine()) != null) {
fileRead.add(line);
}
} catch (IOException exception) {
exception.printStackTrace();
}
I could not find an explanation and those I found I am unsure of. So please confirm my doubts:
I am reading through a file using a while loop and if the line in the file is empty it skips and goes to next line. I just want to make sure the code I am using is correct for the what I just described:
while((strLine = reader.readLine())!= null) <----- While loop that is suppose to read Line by Line
{
if (strLine.isEmpty() == false) <----- Check for empty Line
{
/** My Code **/
}
else
{
/** My Code **/
}
}
Yes! What you are doing is what you want to do. You can just try compiling it yourself, you know. Trial and error. If you could not figure out how to use the reader, as the other answers propose, here you go:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Trial {
public static void main(String[] args) throws IOException {
String strLine;
BufferedReader reader = new BufferedReader(new FileReader(
"/home/user234/folder1/filename"));
while ((strLine = reader.readLine()) != null) {
if (!strLine.isEmpty()) {
System.out.println("notEMPTY");
} else {
System.out.println("EMPTY");
}
}
}
}
yes. it will work fine.
while(/* While scanner has next line */)
{
line = scanner.nextLine();
if( /* line is not equal to null */) {
/* perform code */
}
}
The logic shown in the above code makes sense to what you have described. It should perform what you desire.
The Java Reader does not have a readline() method.
If you want to do specific parsing of tokens you should use the Scanner. Scanner has a nextLine() method to grab each line, but throws an Exception if there is no next line. Therefore you should use Scanner.hasNextLine() for your while condition.
Scanner s = new Scanner("filename.txt");
String line;
while(s.hasNextLine()){ // check for next line
line = s.nextLine(); // get next line
if(line == ""){ // check if line is empty
System.out.println("Empty");
} else {
System.out.println("Not Empty:" + line);
}
}
Here's a live Example using Ideone.
EDIT: The BufferedReader does have a readline() method, as used by #natsirun. Although for any file parsing more complicated than line reading you would prefer the Scanner.
I'm writing a mock stock market in Java, and I want the ability for the user to view stocks purchased. I decided the easiest way to do this is to write to a file. My problem is that every time I run this program and attempt to read from the file, it outputs the path it took to read it. The information I want is correctly written to the file, but it isn't reading from it the way I want.
Here is the code I used for the file reading section:
if (amountOfStocks1 >= 1) {
Scanner stocksBought1 = new Scanner("stocksbought/stocksBought1.txt");
while (stocksBought1.hasNext()) {
String fileRead = stocksBought1.nextLine();
System.out.println(fileRead);
}
stocksBought1.close();
runMenu = 1;
}
There are 7 of these amountOfStocks if/else statements.
I'm not sure if that's enough information. If it's not, tell me what to put on, and I'll do that.
If you can help me fix this problem or if you know an easier way to read and write to files that would be great!
Instead of:
Scanner stocksBought1 = new Scanner("stocksbought/stocksBought1.txt");
Try:
Scanner stocksBought1 = new Scanner(new File("stocksbought/stocksBought1.txt"));
When you only pass a String to the Scanner constructor the Scanner just scans that String. If you give it a File it will scan the contents of the File.
You would probably be better off using the FileReader object. You would use code similar to the following:
import java.io.*;
class FileReaderDemo {
public static void main(String args[]) throws Exception
{
FileReader fr = new FileReader("FileReaderDemo.java");
BufferedReader br = new BufferedReader(fr);
String s;
while((s = br.readLine()) != null) {
System.out.println(s);
}
fr.close();
}
}
In addition, you can use the FileWriter object to write to a file. There's lots of examples on the internet. Easy to find on simple Google search. Hope this helps.
Use FileReader.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReaderExample {
public static void main(String[] args) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\testing.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}