How to solve the java.nio.file.NoSuchFileException? - java

I have a file called "result.csv", from that file i want to read certain data and display them. I have that file in my eclipse project folder itself. Still i'm unable to read the file.
public static void main(String [] args) {
int i=0;
String filename="result.csv";
Path pathToFile = Paths.get(filename);
try (BufferedReader br = Files.newBufferedReader(pathToFile, StandardCharsets.US_ASCII)) {
// read the first line from the text file
String line = br.readLine();
// loop until all lines are read
while (i<10) {
// use string.split to load a string array with the values from
// each line of
// the file, using a comma as the delimiter
String[] attributes = line.split(",");
double x=Double.parseDouble(attributes[8]);
double y=Double.parseDouble(attributes[9]);
System.out.println(GeoHash.withCharacterPrecision(x, y, 10));
// read next line before looping
// if end of file reached, line would be null
line = br.readLine();
i++;
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
OUTPUT:
java.nio.file.NoSuchFileException: result.csv
at sun.nio.fs.WindowsException.translateToIOException(Unknown Source)
at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
at sun.nio.fs.WindowsFileSystemProvider.newByteChannel(Unknown Source)
at java.nio.file.Files.newByteChannel(Unknown Source)
at java.nio.file.Files.newByteChannel(Unknown Source)
at java.nio.file.spi.FileSystemProvider.newInputStream(Unknown Source)
at java.nio.file.Files.newInputStream(Unknown Source)
at java.nio.file.Files.newBufferedReader(Unknown Source)
at com.uvce.cse.searchiot.geohash.TestGeoHash.main(TestGeoHash.java:19)
Can anyone point where exactly i missed? and how can i overcome this or any alternate methods for this method?

The problem is that your default directory at application startup is not what you think it is. Try adding the following line to your code, just after you create the path:
public static void main(String [] args) {
int i=0;
String filename="result.csv";
Path pathToFile = Paths.get(filename);
System.out.println(pathToFile.toAbsolutePath());
That way, you'll see exactly where it is looking for the file.
How to fix it is your decision. You can use a full path spec instead of just a filename, or put the filename in a special "Resources" directory and reference it using a relative path, or move the file to wherever your default directory is.

If your file("result.csv") in the src directory, you should use the "src/result.csv" instead of "result.csv".

The problem there is that java isn't able to find the "result.csv" file in the project folder. Thus, try to use the fully qualified path to the file, e.g. C:\your_folder\project\result.csv in the Path variable. Also I think It would be better to use bufferedreader like this: BufferedReader br = new BufferedReader(new FileReader(insert here the String in which is defined the path to the file)); Check the uses of BufferedReader here

If you're a MacOSX user please type the file path manually instead of copying it from "Get Info".
You'll get something like this if you copied it from "Get Info":
/Users/username<200e><2068><2068>/Desktop<2069>/source.txt

I had the same error caused by escaped characters on windows file path. For example, my application was looking for "C:\Users\david\my%20folder%20name\source.txt" meanwhile the real path was "C:\Users\david\my folder name\source.txt".

Not discarding all possible solutions here, this error also occurs when your running Android Studio on Windows environment and using a project directory on an external hard drive formatted with other than NFTS. ]
If this is the case, simply move your project into the main HDD (NTFS) and reload the project again , this time from the main HDD folder path.

Related

HW Help error **Exception in thread "main" java.lang.NullPointerException** , program runs fine in command line but not eclipse or neat beans [duplicate]

Code:
import java.io.*;
import java.util.Scanner;
public class Driver {
private int colorStrength;
private String color;
public static void main(String[] args) throws IOException {
String line, file = "strength.txt";
File openFile = new File(file);
Scanner inFile = new Scanner(openFile);
while (inFile.hasNext()) {
line = inFile.nextLine();
System.out.println(line);
}
inFile.close();
}
}
This is a small part of a program I am writing for a class (the two private attributes have yet to be used I know) but when I try to run this with the strength.txt file I receive the following errors:
Exception:
Exception in thread "main" java.io.FileNotFoundException: strength.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.util.Scanner.<init>(Unknown Source)
at Driver.main(Driver.java:14)
If anyone with Eclipse could help me figure this out it would be much appreciated!
You've used a relative file path which is relative to your project execution.
If you'd like to do it that way, simply put the strength.txt file in the base directory of your project. Like so:
Alternatively, you could reference the absolute file path on your system. For example, use:
Windows:
C:/dev/myproject/strength.txt
Mac/Unix:
/Users/username/dev/strength.txt
(or whatever the full path may be) instead.
Do this
System.out.println(openFile.getAbsolutePath());
It will show you where JVM expects to find the file and whether it is the folder you expect as well, Accordingly place the file or give the exact location
Use this to see what file path the system is using to reach the relative path
System.out.print(System.getProperty("user.dir"));
Then make sure that the relative path immediately follows this path.
You can also turn that into a string by doing
String filePath = System.getProperty("user.dir");
and then you can just add that to the beginning of the filepath like so,
ImageIcon imageIconRefVar = new ImageIcon(filePath + "/imagepathname");
I found this solved the issue for me when I used it in the path (which seemed odd since that should be the location it is in, but it worked)
You've used a relative file path which is relative to your project execution.
If this works for you, you can change the execution directory from the project root to the binary directory by:
"Run" -> "Run configurations"
In the "Arguments" tab, find "working directory" settings.
Switch from "Default" to "Other".
Click the "Workspace" button and select the project in pop-up window then click "OK"; this will bring you something like $(workspace_loc:proj-1).
Append "/bin" to the end of it; save the configuration.
I need this instead of simply putting files in project root directory when I am doing assignment and the professor requires specific file hierarchy; in addition, this is more portable than absolute path.
Inside the base directory create a folder, name it "res". Place your file inside "res" folder.
use String file = ".\\res\\strength.txt"; to reference the location of your file.
You should use a resource folder to store all the files you use in your program (a good practice).
And make a refrence of that file from your root directory. So the file is present within the package.

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
}

FileNotFoundException in server project in eclipse

I work on a indexing project which create a file dynamically for all words start with same character and the name of that file is created based on first character of the words like:
file "a" contains apple, adapt,air,...
file "b" contains book, bad,bar,...
My project work correctly when I run through application but when I run it through server(tomcat) I got the following error for the given line of the code:
BufferedReader reader = new BufferedReader(new FileReader(getFileName(word)));
INFO: Server startup in 2785 ms
java.io.FileNotFoundException: C (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileReader.<init>(Unknown Source)
at DataLayer.FileRepository.getArrayListPosting(FileRepository.java:54)
I add the path to this word in the following code but I got the same error.
BufferedReader reader = new BufferedReader(new FileReader(getFileName("C:\\code\\"+word)));
what should I do, where should I put this file in eclipse?
This is the image of my files in my project.
Put file "word" in the main Eclipse project directory. Don't worry about adding the path as per your 2nd try.
java.io.FileNotFoundException: C (The system cannot find the file specified)
You probably forgot the : in the path, and accidently made it C\\File which is looking for a directory named C, which doesnt exist.
The problem is that calling function which create the name of the project as argument of fileReader.The solution is :
String str= path+getFileName(word);
BufferedReader reader = new BufferedReader(new FileReader(str));
Any of these two solutions
1________
put the "word" file in the eclipse project directory. i.e the folder that contains the eclipse.exe application file
2_______
File file=new File("theFileFullPath");
According to your program, do it this way => File file= new File("C:\code\"+word)));
then::
BufferedReader reader = new BufferedReader(new FileReader(file.getAbsolutePath()));

Why do I get a FileNotFoundException when ClassLoader.getSystemRessource(filename) gives a result?

My current application needs to get data from a file to initialize its attributes.
It needs to be stored in a file to enable modification to the user.
String strFile = ClassLoader.getSystemResource("myFile.csv").getPath();
if(strFile==null)
throw new Exception("File not find");
BufferedReader br = new BufferedReader(new FileReader(strFile));
//Begin reading file process..
My problem is that strFile is not null but I have a java.io.FileNotFoundException when br is initialized, see the following stack:
java.io.FileNotFoundException: C:\Users\TH951S\My%20Documents\Eclipse\Workspace
\My%20App\bin\myFile.csv
(The system cannot find the path specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileReader.<init>(Unknown Source)
I checked that the file is in the designated path and everything seems correct.
Does anyone knows why this is happening? Or is there another way to get a file when the path is unknown?
Thanks for reading and more for answering,
I solve my issue, one of those that make you feel stupid for not solving it sooner.
URLs are encoding spaces with value %20 and Java do not replace the value by the space character when the FileReader is initialized. Therefore it is necessary to change %20 by " ".
There is also another way of counturning it. It is also possible to initialize the BufferedReader with an InputStreamReader as following:
InputStream in=ClassLoader.getSystemResourceAsStream("myFile.csv");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
Just for completeness: I struggled with the same problem but the result had to be a File object (because I needed the size of the file).
URL url = ClassLoader.getSystemResource("myFile.csv");
File file = new File(url.toURI());
System.out.println("Correct path: " + file.getAbsolutePath());
System.out.println("Size of file: " + file.length());
The solution is inspired by sysLoader.getResource() problem in java.
I was surprised that I had to go over so many classes but I didn't find a closer solution.

java.io.IOException: The system cannot find the path specified writing a textfile

I'm writing a program where I'm trying to create a new text file in the current directory, and then write a string to it. However, when trying to create the file, this block of code:
//Create the output text file.
File outputText = new File(filePath.getParentFile() + "\\Decrypted.txt");
try
{
outputText.createNewFile();
}
catch (IOException e)
{
e.printStackTrace();
}
is giving me this error message:
java.io.IOException: The system cannot find the path specified
at java.io.WinNTFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(Unknown Source)
at code.Crypto.decrypt(Crypto.java:55)
at code.Crypto.main(Crypto.java:27)
Because of this I cannot write to the file because it naturally does not exist. What am I doing wrong here?
If you're working with the File class already, consider using its full potential instead of doing half the work on your own:
File outputText = new File(filePath.getParentFile(), "Decrypted.txt");
What's the value of filePath.getParentFile()? What operating system are you using? It might be a better idea to join both paths in a system-independent way, like this:
filePath.getParentFile() + File.separator + "Decrypted.txt"
It should be created as a sibling of the file pointed by filePath.
for example if
File filePath = new File("C:\\\\Test\\\\a.txt");
Then it should be created under Test dir.

Categories