Error in reading from file (Java) - java

I posted a similar question here: Read from a file containing integers - java but couldn't get a decent reply.
Now I have written this new code which only reads a file and outputs the result.
I get a FileNotFoundException whenever I try to read from a file. The code is below:
import java.io.*;
public class second {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
File f = new File("C:\\Users\\Haroon\\workspace\\ppp\\temperature.txt");
FileReader file = new FileReader(f);
BufferedReader buf = new BufferedReader(file);
String s = null;
while((s = buf.readLine()) != null){
System.out.println(s);
}
}
}
This is strange because the file is in the project's folder.
Any help would be appreciated.

That should work. Go to the location of the file, copy the path, paste it in your code, and escape the slashes. You are missing something.
Also check that the name/extension of the file is correct, you could have something like "temperature.txt.txt".

I don't know why you are unable to read the file. Its working fine on my system. Since you are making you project in eclipse. I will post a workaround here.
System.out.println(System.getProperty("user.dir"));
Use this command to find the current user directory at the time of execution. Now directly place the file in that user directory. Now you can directly read the file just by its name.
For eg:
File f = new File("temperature.txt");
Also as mentioned by 'lxxx' do check the file name and the extension by enabling show file extension option in Windows.

Related

File not found exception error in Java

I'm trying to read a file but I can't seem to make it work. It shows an error: "File not found exception". The system cannot find the file specified. I enclosed the code below. Can anyone solve this issue?
package trailfiledemo;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
/**
*
* #author VIGNESH
*/
public class Trailfiledemo {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException, IOException {
// TODO code application logic here
FileReader fr=new FileReader("C:\\Users\\VIGNESH\\Documents\\ga and pso\\hellodata.txt");
int i;
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
}
}
Check if your file exists within the designated file path as it needs to match. Another possibility that Joik mentioned above, is your compiler might not have permission to access the file within the path given. You could try an alternative file path if that is the case.
FileNotFound exception has wrong name. It may appear not only in case the file is absent, so there is an ambiguity.
There are three cases where a FileNotFoundException may be thrown:
1.The file does not exist.
2.The file is actually a directory.
3.The file cannot be opened. It may have no read access in your OS.
You need to check all 3 fail cases to be sure about the root of the issue. Documentation page contains some details:
https://docs.oracle.com/javase/7/docs/api/java/io/FileNotFoundException.html
I implemented your code and only changed your username to mine and it compiled like a charm. Read everything in the file and ended succesfully.
Try:
Click on Run > Clean and Build Project maybe it didn't take one of your changes.
Other things you might want to try:
use a buffered reader:
try (BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\VIGNESH\\Documents\\ga and pso\\hellodata.txt"))) {
String line;
while ((line = br.readLine()) != null)
System.out.print(line + "\n");
}
Or you could move the file into the same folder as the code and use this path '"src\stackoverflow\hellodata.txt"' stackoverflow => your packageĀ“s name

How do I create a File object in Java w/out using an absolute path name?

This is the path I'm using now:
C:\Users\Sabrina\Documents\NetBeansProjects\TriangleSumRecursion\lab4Data.txt
I tried just using the following:
C:\TriangleSumRecursion\lab4Data.txt
and
TriangleSumRecursion\lab4Data.txt
If I use either of those two Java will say "(The system cannot find the file specified)"...
TriangleSumRecursion is the java package that I'll turn in.
You can import the particular file into the project, and then try using TriangleSumRecursion\lab4Data.txt
You can import the file by right clicking on your project folder from your IDE, and then click on import. Follow the instructions and give the path of your file in it.
i hope it works for you.
First of all, use Slashes ('/'), not Backslashes ('\') in Javacode.
But besides of that, Java can handle absolute and relative paths.
I tried just using the following: C:\TriangleSumRecursion\lab4Data.txt
This is not the right absolute path, if there is no folder 'TriangleSumRecursion' in C:\. Your working path example is the only right one.
and TriangleSumRecursion\lab4Data.txt
Here you try this as a relative path. Java starts its search in the folder your file, running the code, is located. So this would work, if your java file was in 'C:\Users\Sabrina\Documents\NetBeansProjects'.
But since I think your file is in 'TriangleSumRecursion', the path you are looking for is simply 'lab4Data.txt'.
You could try the following reading your file line by line, by first reading the file through a file reader, that is then fed to the buffered reader. Then you can create a string buffer, and as the program reads each line of the file it will append it to the string buffer. To check if it was successful just simply close the file reader and use the toString() method to display the contents of the file.
`public static void main(String[] args) {
try {
File file = new File("lab4Data.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
stringBuffer.append("\n");
}
fileReader.close();
System.out.println("File is:");
System.out.println(stringBuffer.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}`
C:\TriangleSumRecursion\lab4Data.txt is an absolute path, so this will not identify your file which is not at this location.
You are more than probably in directory C:\Users\Sabrina\Documents\NetBeansProjects\TriangleSumRecursion, therefore a simple:
Paths.get("lab4Data.txt")
will give you a Path to your file (this is 2015; use java.nio.file and drop File).
But this is Windows and there are some strange things with Windows... Another way to access your file would be:
Paths.get("c:lab4data.txt")
Which is a path which has a root (c:) but which is not absolute (since such a path cannot be used to uniquely identify a resource on the FileSystem.
See the Files class on how to open, for instance, an InputStream or a BufferedReader from this file. And note that if the file does not exist the matching methods will throw a NoSuchFileException.
Last but not least, use a try-with-resources statement:
try (
final BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8);
) {
// use the reader here
}

Data reading from file, file name pass through Commandline argument in java

I have a .txt file assume it name My. I need to read this file content.I pass the file through command Line argument. What should I do in the Command prompt to pass the file to args[] array. Please help..............
You can get the file name with command line arguments:
java -jar myapp.jar abc.txt
or
java a.b.c.MyApplication abc.txt
will place abc.txt into args[0] of
public static void main(String[] args)
Then you can open the File and read it from Java code.
If you want the file contents (and not write Java code to read them), you could get them via System.in:
java -jar myapp.jar < abc.txt
(the above depends a bit on what kind of shell and OS you are using)
InputStream data = System.in;
Sometimes it's difficult to know where to start, but this question in its parts has been answered many times. However, perhaps to help you, it's best to point you in the right direction.
The steps you want are:
1) Get the String which represents the files path from the args array, perhaps something like:
String filePath = args[0];
However, you will want to also check that there is an item in the args to prevent the possibility of getting an exception when reading from the args (if nothing was passed from the command line) e.g:
String filePath;
if(args.length > 0){
filePath = args[0];
}else{
// do something to handle the error, probably exit the program?
}
For any more details on this, see here: Link to java tutorial
2)
Then, you want to make a File object from that string using the File constructor. Link to javadoc
File inputFile = new File(filePath);
3)
Then you need to read that file, line by line. For that I will point you to another SO answer, as there are many ways to do this:
Reading from a file - SO question
Hope this helps.
this is the code you probably want
String path =arr[0]; //first approach
/*Scanner in = new Scanner(System.in);
System.out.println("Enter the path of the file..."); // whole block command second approac
String path = in.nextLine(); */
File file = new File(path);
//apply your logic i just did some reading and writing to a file
/*BufferedReader inputStream = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
PrintStream out = new PrintStream(new FileOutputStream("a.txt"));
while(true)
{
String line = inputStream.readLine();
if(line == null)
break;
else
out.println(line);
}
*/
if you use the first approach run the program as
java className path_of_file
In second approach it will ask you for file path at runtime then you can enter the path of the file. just run like java className

Java Text File I/O Location

I have looked at other threads on where Java looks for files, but I still find myself confused.
I have a program, created in Eclipse (Juno) as a java project. I have made no modifications to anything else, and only have a main class for now.
When the program runs, it takes three inputs: a number, and two strings. The first string is the name of the file it has to read input from, the second is the file it has to put output to.
If I pass in "input.txt" for the input string, and have a file called input.txt, where should it be for Java to find it? I have tried putting it in src, bin, and in the project root. Currently, I am trying to access the file as follows:
File input = new File(args[1]);
Where args[1] is the first string passed to the program at the start. When I do this, I get an error "java.io.FileNotFoundException: input.txt (The system cannot find the file specified)"
Where should I be putting the file so that Java can find it?
Here is the relevant code:
public class main {
public static int runs;
public static File input;
public static File output;
public static String line1;
public static String line2;
public static String line3;
public static String reactions;
/**
* #param args
*/
public static void main(String[] args){
if(args.length != 3)
System.out.println("Please provide 3 arguments.");
runs = Integer.parseInt(args[0]);
File input = new File(args[1]);
File output = new File(args[2]);
System.out.println(runs);
System.out.println(input);
try {
Scanner sc = new Scanner(input);
For questions like this, try using the getAbsolutePath() method:
File input = new File(args[1]);
System.out.println(input.getAbsolutePath());
This shows you where the file object thinks the file is. That's where you should put the file... or perhaps modify the input argument accordingly so the program looks for the file in the place where you want the file to be.
You just need to put that input file in root folder of your project.
UPDATE :
As you are using scanner to get user input. then hide the code which your are using for args ie command line arguments.
Scanner sc = new Scanner(input);
runs = sc.nextInt(); // This will store your input line
in = sc.next(); // This will store your input file name
out = sc.next(); // This will store your output file name
If file name is not absolute (does not start with / on *nix and C:\ on Windows), then it is looked in current working directory. Java program may get its current working directory using System.getProperty ("user.dir").
In Eclipse you should explicitly set the execution directory for a run configuration.
The directory used by default can depend on project configuration, packaging, output directory, etc. so it's best to either (a) use an absolute path (e.g., prefaced with a c:\ or / etc.) or (b) set it in the run config.

The system cannot find the file specified in java

I am making a program that opens and reads a file.
This is my code:
import java.io.*;
public class FileRead{
public static void main(String[] args){
try{
File file = new File("hello.txt");
System.out.println(file.getCanonicalPath());
FileInputStream ft = new FileInputStream(file);
DataInputStream in = new DataInputStream(ft);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strline;
while((strline = br.readLine()) != null){
System.out.println(strline);
}
in.close();
}catch(Exception e){
System.err.println("Error: " + e.getMessage());
}
}
}
but when I run, I get this error:
C:\Users\User\Documents\Workspace\FileRead\hello.txt
Error: hello.txt (The system cannot find the file specified)
my FileRead.java and hello.txt where in the same directory that can be found in:
C:\Users\User\Documents\Workspace\FileRead
I'm wondering what I am doing wrong?
Try to list all files' names in the directory by calling:
File file = new File(".");
for(String fileNames : file.list()) System.out.println(fileNames);
and see if you will find your files in the list.
I have copied your code and it runs fine.
I suspect you are simply having some problem in the actual file name of hello.txt, or you are running in a wrong directory. Consider verifying by the method suggested by #Eng.Fouad
You need to give the absolute pathname to where the file exists.
File file = new File("C:\\Users\\User\\Documents\\Workspace\\FileRead\\hello.txt");
In your IDE right click on the file you want to read and choose "copy path"
then paste it into your code.
Note that windows hides the file extension so if you create a text file "myfile.txt" it might be actually saved as "myfile.txt.txt"
Generally, just stating the name of file inside the File constructor means that the file is located in the same directory as the java file. However, when using IDEs like NetBeans and Eclipse i.e. not the case you have to save the file in the project folder directory. So I think checking that will solve your problem.
How are you running the program?
It's not the java file that is being ran but rather the .class file that is created by compiling the java code. You will either need to specify the absolute path like user1420750 says or a relative path to your System.getProperty("user.dir") directory. This should be the working directory or the directory you ran the java command from.
First Create folder same as path which you Specified. after then create File
File dir = new File("C:\\USER\\Semple_file\\");
File file = new File("C:\\USER\\Semple_file\\abc.txt");
if(!file.exists())
{
dir.mkdir();
file.createNewFile();
System.out.println("File,Folder Created.);
}
When you run a jar, your Main class itself becomes args[0] and your filename comes immediately after.
I had the same issue: I could locate my file when provided the absolute path from eclipse (because I was referring to the file as args[0]). Yet when I run the same from jar, it was trying to locate my main class - which is when I got the idea that I should be reading my file from args[1].

Categories