this is the code that i have found in the internet for reading the lines of a file and also I use eclipse and I passed the name of files as SanShin.txt in its argument field. but it will print :
Error: textfile.txt (The system cannot find the file specified)
Code:
public class Zip {
public static void main(String[] args){
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("textfile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
please help me why it prints this error. thanks
When you just specify
"textfile.txt"
the operating system will look in the program's working directory for that file.You can specify the absolute path to the file with something like
new FileInputStream("C:\\full\\path\\to\\file.txt")
Also if you want to know the directory your program is running in, try this:
System.out.println(new File(".").getAbsolutePath())
Your
new FileInputStream("textfile.txt")
is correct. If it's throwing that exception, there is notextfile.txt
in the current directory when you run the program. Are you sure the file's name isn't actuallytestfile.txt
(note thes
, notx
, in the third position).Off-topic: But your earlier deleted question asked how to read a file line by line (I didn't think you needed to delete it, FWIW). On the assumption you're still a beginner and getting the hang of things, a pointer: You probably don't want to be using
FileInputStream
, which is for binary files, but instead use theReader
set of interfaces/classes injava.io
(includingFileReader
). Also, whenever possible, declare your variables using the interface, even when initializing them to a specific class, so for instance,Reader r = new FileReader("textfile.txt")
(rather thanFileReader r = ...
).