This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I was writing code for a small tool that removes a user-given string from a file whose name is fed to the program from the command line. But when run, it throws a NullPointerException. I can't figure out why. Please help me solve this mystery. Thank you very much. This code is as follows.
/**
* Remove certain lines from a text file.
*/
import java.util.*;
import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
public class LineCutter {
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Usage: java LineCutter filename");
System.exit(1);
}
System.out.println("Enter the line to be removed:");
Scanner lineToRemove = new Scanner(System.in);
lineToRemove.nextLine();
FileReader fr = null;
FileWriter fw = null;
BufferedReader br = null;
BufferedWriter bw = null;
try {
fr = new FileReader(args[1]);
br = new BufferedReader(fr);
fw = new FileWriter(new File("output.txt"));
bw = new BufferedWriter(fw);
String line = br.readLine();
while(line != null) {
if (!line.equals(lineToRemove))
bw.write(line);
line = br.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
br.close(); // NullPointerException
fw.close();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("Operations finished.");
}
}
If fr = new FileReader(args[1]) throws an exception then br will be null when you attempt to call br.close() and the NullPointerException will hide the actual problem. Your problem is most likely the use of 1 as the index causing an ArrayIndexOutOfBoundsException. You expect only one element in the args array, so you should be using args[0]. Remember, arrays are zero-based.
Also, you should be using a try-with-resources statement. It handles closing everything for you automatically in a null-safe manner. For example:
try (BufferedReader br = new BufferedReader(new FileReader(args[0]));
BufferedWriter bw = new BufferedWriter(new FileWriter(new File("output.txt")))) {
// I/O code...
} catch (IOException ex) {
ex.printStackTrace();
}
Not sure what the following code is supposed to be doing:
System.out.println("Enter the line to be removed:");
Scanner lineToRemove = new Scanner(System.in);
lineToRemove.nextLine();
You don't do anything with result of lineToRemove.nextLine(). Though later you test if a String is equal to lineToRemove, which will always be false. Perhaps you mean:
String lineToRemove = new Scanner(System.in).nextLine();
Probably because fr = new FileReader(args[1]); is throwing an exception (probably because it can't find the file specified in args[1]), and so br continue to be null, and so you are invoking .close() in a null object.
I would also point out that here:
if (!line.equals(lineToRemove))
bw.write(line);
you are invoking equals between a String and a Scanner
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();
}
Alright so I have a very small program I'm working on designed to take the contents of a text file, test.txt, and put them in another empty file testCopied.txt . The trick is that I want to use Scanner and printWriter as I am trying to understand these a bit better.
Here is what my code looks like:
import java.io.*;
import java.util.*;
public class CopyA
{
public static void main(String [] args)
{
String Input_filename = args[0];
String Output_filename = args[1];
char r = args[2].charAt(0);
try
{
Scanner sc = new Scanner(new File(Input_filename));
FileWriter fw = new FileWriter(Output_filename);
PrintWriter printer = new PrintWriter(fw);
while(sc.hasNextLine())
{
String s = sc.nextLine();
printer.write(s);
}
sc.close();
}
catch(IOException ioe)
{
System.out.println(ioe);
}
}
}
This compiles, but when I look at testCopied.txt it is still blank, and hasn't had test.txt's content transferred to it. What am I doing wrong? Java IO is pretty confusing to me, so I'm trying to get a better grasp on it. Any help is really appreciated!
You have missed out flush() and close() for the PrintWriter object which you need to add
and then use the line separator using System.getProperty("line.separator") while writing each line into second file.
You can refer the below code:
PrintWriter printer = null;
Scanner sc = null;
try
{
String lineSeparator = System.getProperty("line.separator");
sc = new Scanner(new File(Input_filename));
FileWriter fw = new FileWriter(Output_filename);
printer = new PrintWriter(fw);
while(sc.hasNextLine())
{
String s = sc.nextLine()+lineSeparator; //Add line separator
printer.write(s);
}
}
catch(IOException ioe)
{
System.out.println(ioe);
} finally {
if(sc != null) {
sc.close();
}
if(printer != null) {
printer.flush();
printer.close();
}
}
Also, ensure that you are always closing resources in the finally block (which you have missed out for Scanner object in your code).
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();
}
}
}
}
This question already has answers here:
How to append text to an existing file in Java?
(31 answers)
Closed 8 years ago.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class test3 {
public static void main(String[] args) {
//write
try {
FileWriter fw = new FileWriter("C:\\Users\\Danny\\Desktop\\Credits.txt");
PrintWriter pw = new PrintWriter (fw);
pw.println("This is just some test data");
pw.close();
}
catch (IOException e){
System.out.println("Error!");
}
//read
try {
FileReader fr = new FileReader("C:\\Users\\Danny\\Desktop\\Credits.txt");
BufferedReader br = new BufferedReader (fr);
String str;
while ((str = br.readLine()) != null ) {
System.out.println(str + "\n");
}
br.close();
}
catch (IOException e){
System.out.println("File not found!");
}
}
}
This works but over writes the text file each time with the new input. How do I stop this over writing so that all information is stored in the file like an archive.
Pass true to your FileWriter like this -
FileWriter fw = new FileWriter("C:\\Users\\Danny\\Desktop\\Credits.txt",true);
The second parameter to the FileWriter constructor will tell it to append to the file.
Docs --> http://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html#FileWriter(java.lang.String,boolean)
Open the file in Append mode the next time you want to write to file.
FileWriter fw = new FileWriter("C:\\Users\\Danny\\Desktop\\Credits.txt",true);
Use:
Files.newBufferedWriter(Paths.get("yourfile"), StandardCharsets.UTF_8,
StandardOpenOption.APPEND);
This question already has answers here:
BufferedWriter not writing everything to its output file
(8 answers)
Closed 8 years ago.
This is a code snippet but basically what I want to do is read from a file named 'listings.txt' and write to a file named 'overview.txt'. I want to take the information out of 'listings.txt' and put them into 'overview.txt' as is (I will figure out the rest later).
The file 'overview.txt' is created and appears to loop through the file 'listings.txt' and write to 'overview.txt'. However, once I open the file 'overview.txt' it is empty. Could someone go through a quick glance at my code and spot something erroneous?
package yesOverview;
import java.io.BufferedReader;
import java.io.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
public class yesOverview {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String strInput = "foo.bar";
System.out.print("Please enter the listings file (the full path to the file): ");
strInput = input.next();
//This makes sure that the inputed file is listings.txt as required for KET1 task 2
while (strInput.contains("listings.txt") == false) {
System.out.print("Incorrect file. Please enter listings file(the full path to the file): ");
strInput = input.next();
}
infos(strInput);
input.close();
}
public static void infos(String strInput) {
Scanner input2 = new Scanner(System.in);
System.out.print("Please enter the overview.txt file (the full path to the file): ");
String strInput2 = "foo.bar";
strInput2 = input2.next();
//This also makes sure that the overview.txt file is provided.
while (strInput2.contains("overview.txt") == false) {
System.out.print("Incorrect file. Please enter overview file(the full path to the file): ");
strInput2 = input2.next();
}
//Creates the file f then places it in the specified directory.
File f = new File(strInput2);
try {
//Creates a printerwriter out that writes to the output file.
PrintWriter out = new PrintWriter(strInput2);
} catch (FileNotFoundException ex) {
Logger.getLogger(KETTask2Overview.class.getName()).log(Level.SEVERE, null, ex);
}
//String that holds the value of the next line.
String inputLine = "";
//Creates the Buffered file reader / writer.
try {
BufferedReader in = new BufferedReader(new FileReader(strInput));
FileWriter fstream = new FileWriter(strInput2);
BufferedWriter out = new BufferedWriter(fstream);
while (in.readLine() != null) {
out.write(in.read());
}
in.close();
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
}
}
Try this
Close the BufferedWriter stream (ie out.close() )
try and use nextLine() instead of next(), as next() only takes in a single word, but for a complete line use nextLine(), though this doesnt seem to be the problem here.
What i do when i have to read and write to files, i normally follow these steps
For Reading from a file
File f = new File("my.txt");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String s = null;
while ((br.readLine())!=null) {
// Do whatever u want to do with the content of the file,eg print it on console using SysOut...etc
}
br.close();
For Writing to a file:
Boolean isDone = true;
Scanner scan = new Scanner(System.in);
File f = new File("my.txt");
FileWriter fr = new FileWriter(f);
BufferedWriter br = new BufferedWriter(fr);
while (isDone) {
if (!isDone) {
br.write(new Scanner(System.in).nextLine());
}
}
public static long copy (Reader input, Writer output) throws IOException {
char[] buffer = new char[8192];
long count = 0;
int n;
while ((n = input.read( buffer )) != -1) {
output.write( buffer, 0, n );
count += n;
}
return count;
}
Usage Example:
copy( reader, new FileWriter( file ) );
You're not closing out.
The finally block for the writeList method cleans up and then closes the BufferedWriter.
finally {
if (out != null) {
System.out.println("Closing BufferedWriter");
out.close();
} else {
System.out.println("BufferedWriter not open");
}
}