FileReader can't find file despite file existing - java

I am trying to use the opencsv library however I am getting stuck early on with FileReader not being able to find the csv I am using to test with.
I have the following code:
import java.io.File;
import java.io.FileReader;
public class Test {
public static void main(String[] args) {
File f = new File("demo.csv");
if(f.exists() && !f.isDirectory()) {
System.out.println("File exists");
}
else {
System.out.println("File does not exist");
}
FileReader reader = new FileReader("demo.csv");
}
}
I am getting a FileNotFoundException error on the FileReader:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unhandled exception type FileNotFoundException at Test.main(Test.java:19)
despite having checked the file exists in the correct directory using f.exist. Done a load of searching and found nothing to explain it.
Can anyone help with this?

check if the file extension is visible and your file is not named demo.csv.csv. Happend to me and took me a while to resolve.

By default, the compiler would look for "demo.csv" in the root directory. Make sure that you clearly specify the path in FileReader parameter.
The same code does work in my case (provided demo.csv in right under the root directory)

Related

How to give access to Intellij-Idea to write files?

I am trying to write files to my windows 7 computer using IntelliJ IDEA. I am using the File and Filewriter programs to do this. But I am receiving an error message claiming to not have access to my folders in order to do this.
I have tried looking at other tutorials and people with a similar issue but I have not seen anyone with this issue so far. I have also looked at IntelliJ's permissions in the firewall and they are all in check. I also tried using different derectories such as my SRC folder and others, to no prevail.
public class Main {
public static void main(String[] args) throws IOException {
//fori loop
for(int a=0;a<1000;a++) {
//writing to desktop
File file = new File("C:\\Users\\BlahBlah\\Desktop\\");
FileWriter fw = new FileWriter(file);
fw.write("Hey you!");
fw.close();
}
}
}
I should expect a outflow of 1000 files to be written to my pc but instead I get an error telling me "Access is denied". The entire error is listed below.
Exception in thread "main" java.io.FileNotFoundException: C:\Users\BlahBlah\Desktop (Access is denied)
The exception is clear, it's telling you that there is not file there. Indeed C:\Users\BlahBlah\Desktop is not a file path, you should have something like:
file = new File("C:\\Users\\BlahBlah\\Desktop\\test.txt");
And you're creating a File 1000 times, I think that you might have an error there as well.
Try adding index a value to the filename with an extension say desktop1.txt
for(int a=0; a<1000;a++)
{
FileWriter fw=new FileWriter("D:\\ desktop"+a+".txt");
fw.write("hey file."+a);
fw.close();
}

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

File default location

Why the program search the file:
File FILE_PATH = new File("‪‪C:\\Users\\home\\Desktop\\DbWord.txt");
System.out.println(FILE_PATH.exists());
System.out.println(FILE_PATH.getAbsoluteFile());
FileInputStream fIn = new FileInputStream(FILE_PATH);
Scanner reader = new Scanner(fIn);
at: C:\Users\home\Documents\NetBeansProjects\MyDatabase\‪‪C:\Users\home\Desktop\DbWord.txt
How can i counteract the default location?
If something in this post not good, please tell me and no negative vote.
Thanks!
why negative votes??????????????? whats your problems??????????
Please double check your error details. You might have seen something like the below error. Actually the program is not searching for the file "C:\Users\home\Documents\NetBeansProjects\MyDatabase\‪‪C:\Users\home\Desktop\DbWord.txt", it is trying to locate the file "C:\Users\home\Desktop\DbWord.txt" which does not exists in your machine. You are seeing "C:\Users\home\Documents\NetBeansProjects\MyDatabase\‪‪C:\Users\home\Desktop\DbWord.txt" along with the error because you have already used System.out.println(FILE_PATH.getAbsoluteFile()); statement in your code.
false
Exception in thread "main" java.io.FileNotFoundException: ‪‪C:\Users\home\Desktop\DbWord.txt (The filename, directory name, or volume label syntax is incorrect)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
C:\Users\home\Documents\NetBeansProjects\MyDatabase\‪‪C:\Users\home\Desktop\DbWord.txt
at com.stackoverflow.answer.SimpleFileHelper.main(SimpleFileHelper.java:17)
Hope you are clear now.
There are three main chances where a FileNotFoundException may be thrown.
The named file does not exist.
The named file is actually a directory not file.
The named file cannot be opened for reading due to some reason.
The first two reasons are unlikely based on your description, please check the third point using file.canRead() method.
If the test above returns true, I would suspect the following:
You might have forgotten to explicitly throw or catch the potential exception (i.e., FileNotFoundExcetion). If you work in an IDE, you should have got some complaint from the compiler. But I suspect you didn't run your code in such an IDE.
Try the following code and see if the exception would be gone:
package com.stackoverflow.answer;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class SimpleFileHelper {
public static void main(String[] args) throws FileNotFoundException {
File FILE_PATH = new File("C:/Users/home/Desktop/DbWord.txt");
System.out.println(FILE_PATH.exists());
System.out.println(FILE_PATH.getAbsoluteFile());
FileInputStream fIn = new FileInputStream(FILE_PATH);
Scanner reader = new Scanner(fIn);
}
}

java 'File' Object not making the directory and file

I was trying to make a directory and file using java with File object as:
import java.io.*;
class CreateFile{
public static void main(String[] args) throws IOException{
File f = new File("File/handling/file1.txt");
if(!f.exists())
f.createNewFile();
}
}
but its showing error (see below) and unable to make it, the path and file name doesn't existed before execution. I don't know where am I going wrong, someone please clarify whats the mistake and how to resolve it? It might be I need to know something about File object, so please do tell me...
See error:
Exception in thread "main" java.io.IOException: The system cannot find the path
specified
at java.io.WinNTFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:947)
at CreateFile.main(CreateFile.java:6)
The error is telling you that either there is no File directory relative to where you're running this, or there is but it doesn't have a handling subdirectory. In this case, exists returns false and so you call createNewFile to try to create the file, but the directory in which you're trying to create it doesn't exist, and so it throws an exception.
You can use mkdirs to create the directories if necessary, like so:
import java.io.*;
class CreateFile{
public static void main(String[] args) throws IOException{
File f = new File("File/handling/file1.txt");
if(!f.exists()) {
f.getParentFile().mkdirs(); // This is a no-op if it exists
f.createNewFile();
}
}
}

Passing in a file name / directory into command line in Java

I'm trying to do some processing on whether the user enters a (1) file name, or (2) directory name into the command line. Anything else should throw an error. Starting with the simplest case, I wrote this:
import java.io.*;
import java.util.*;
public class RemoveDuplicates {
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Program accepts one command-line argument. Exiting!");
System.exit(1);
}
File f = new File(args[0]);
if (f.isDirectory()) {
System.out.println("is directory");
}
else if (f.isFile()) {
System.out.println("is file");
}
else {
System.out.println("Shouldn't happen");
}
}
}
at the command line, I type: java RemoveDuplicates example.txt
and I get the reuslts, "Shouldn't happen." I also tried java RemoveDuplicates "example.txt" and that doesn't work either. So I was wondering if my code is wrong, or how I'm passing it into the command line is wrong for starters.
Secondly, how do you pass in a directory name? Like if your directory was myDirectory, is it the same thing: java RemoveDuplicates myDirectory
Third, why if I put my File f = new File(args[0]) into a try block and have a catch block, I get a compile error about what is in my try block never throws an exception. I thought File threw an exception? Thanks in advance!
Are you sure example.txt exists in your working directory? Try adding the following and see what happens.
File f = new File(args[0]);
if (!f.exists()) {
System.out.println("does not exist");
}
You have that right.
Actually, I don't get this error. How did you do the try/catch?
So I was wondering if my code is wrong, or how I'm passing it into the command line is
wrong for starters
Is that file present in your working directory? Something which doesn't exist is neither a file nor a directory. Try creating a sample text file with the same name and then invoking your program.
how do you pass in a directory name
Pass in a fully qualified string which represents your directory (e.g. java MyProg "c:\testdir\mydir") pass in a directory path relative to your current working directory (e.g. java MyProg testdir/mydir)
File f = new File(args[0]). I thought File threw an exception?
Creating a new File object doesn't create a physical file hence no IOException is thrown as you expected. It is only when you try to open a file for reading or writing a FileNotFoundException is thrown. Hence it's a good practice to always check for the existence of a File before using it for IO.
I compiled & ran your program. It is working as expected.
C:\upul\eclipse\src\Test\src>java RemoveDuplicates RemoveDuplicates.java
is file
C:\upul\eclipse\src\Test\src>java RemoveDuplicates c:\upul
is directory
You need to type java RemoveDuplicates.java example.txt.
Correct.
You should be able to do that as anything can throw RuntimeException which is a subclass of Exception.

Categories