Question:
what's wrong with this java program?
sulav.aryal
2007-06-11 22:32:42 UTC
import java.io.*;
class CopyBytes
{
public static void main(String args[])
{
FileInputStream infile=null;
FileOutputStream outfile=null;
byte byteRead;
try
{
infile=new FileInputStream("in.txt");
outfile=new FileOutputStream("out.txt");
do
{
byteRead=(byte)infile.read();
outfile.write(byteRead);
}
while(byteRead!=-1);
}
catch(FileNotFoundException e)
{
System.out.println(e);
}
catch(IOException e)
{
System.out.println(e);
}
finally
{
try
{
infile.close();
outfile.close();
}
catch(IOException e)
{}
}
}
}

/*//"error it says" it compile though:- java.io.FileNotFoundException:in.txt( The system cannot find the file specified)
Exception in thread "main" java.lang.NullPointerException at CopyBytes.main(CopyBytes.java:32) */
Three answers:
minus71
2007-06-14 10:14:44 UTC
No, it isn't supposed to create input stream which do not exists.



FileInputStream do not create an empty stream if the file is missing. So ... if you whant to create it 'on the fly' just instance the FileInputStream from a File and not from a 'String', and before calling the constructor just test if the file exists and if not create it, by first Opening an output stream to it and writing something ecc...
2007-06-12 05:42:56 UTC
Your file isn't in the right directory. The file needs to be in the directory that you are executing the file from.

Also its a bad idea to refer to a FileInputStream or an FileOutputStream before while in a try block that catches a FileNotFoundException.





java.lang.NullPointerException is becase new FileInputStream("in.txt"); returns null since it can't find the file.



good luck.
>:niranjan
2007-06-12 05:50:00 UTC
This program tries to copy bytes from the file "in.txt" into a new file called "out.txt". So before running the program, ensure that the file "in.txt" exists.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...