This code throws FileNotFoundException.
Edit: As requested I have included the full StackTrace.
import java.io.FileInputStream;
import java.io.InputStream;
public class ReadFile{
public static void main(String[] args){
InputStream inputstream = new FileInputStream("C:\\file.txt");
}
}
The file "file.txt" is at that location though. I would like to post a screenshot of this as requested, but I can't because I need at least 10 reputation points.
If you are 100% certain that the file exists and you're still getting a FileNotFoundException, than most likely your user or the user running Java has no permission to access this file (since I am using German Windows the dialog is in German, but as you can see "Benutzer" (which is Users) have a denied right to read and execute the file a.txt:
This however, results in a a FileNotFoundException with a localized error message returned :
Exception in thread "main" java.io.FileNotFoundException: C:\a.txt (Zugriff verweigert)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:131)
at java.io.FileInputStream.<init>(FileInputStream.java:87)
at Threadstuff.main(Threadstuff.java:50)
Zugriff verweigert means "access denied". If that isn't the problem either, I guess you should post your full StackTrace.
The other option I mentioned in my comment is an explorer option ("View" -> "Options") in the Folder and Search options -> View:
(roughly translates to "Hide extensions for known extensions")
If this is enabled, the filenames in the explorer are losing their extensions in the view. Meaning that they are shown as "file" instead of "file.txt" - which sometimes leads to the mistake of creating a "file.txt.txt" when renaming a file. And is/was also often used to trick users into thinking they were open a different kind of file (.pdf.exe) - mostly used by bad guys.
Is this really the full Filepath? Better check that one.
Also I'd recommend putting files that are to be read by your program e.g. Textfiles, Images and such into the classpath of your project so when you pack and export it the file paths are not obstructed by being on somebody else's PC where that file does not exist on that path and so on.
This answer suggest you transform the Path of the file to a java conform URL path.
Try the below one.
InputStream inputstream = new FileInputStream("C:"+File.separator+"file.txt");
A better approach would be
File file = new File("C:"+File.separator+"file.txt");
if(file.exists()) {
//Read the file
}
else {
System.out.println("File does not exist);
}
To ensure whether file exists or not in windows, press windows button + r and then paste the file path you have mentioned and after that press enter key. If file is in that location, a notepad with file contents will be opened.
Related
I am getting the exception (java.nio.file.FileSystemException) while I run the this code
public String getScreenShotAsBase64() throws IOException {
File source = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
String path = System.getProperty("user.dir") + "/Screenshots/image.png";
FileUtils.copyFile(source, new File(path));
byte[] imageBytes = IOUtils.toByteArray(new FileInputStream(path));
return Base64.getEncoder().encodeToString(imageBytes);
}
when I try to run the method it is not working throws exception.
The cause of your problem is that Windows won't let your application open the "Screenshots/image.png" file for writing because something else already has it open. It just won't. See File Locking for an overview of Windows file locks and their purpose.
This SuperUser Q&A gives a number of ways to figure out which other application holds the file lock:
Find out which process is locking a file or folder in Windows
Your use of Selenium in this instance is (probably) not apropos.
You will most likely need to do one of the following to resolve this.
Change your application to write the screenshot to another file if the first target file it chooses is locked.
Tell the user that your application can't write the file. The user message could suggest that they need to close whatever other application it is that has the image file open at the moment.
If the other application is Windows itself (for some reason) you will probably need to rethink what you trying to do.
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.
I am attempting to read from a file, however the console gives me this error.
Exception in thread "main" java.io.FileNotFoundException: dataEx.txt (The system cannot find the file specified)
This is the code that I am executing.
import java.io.*;
import java.util.*;
public class ReadTest {
public static void main(String[] args) throws IOException {
BufferedReader f = new BufferedReader(new FileReader("dataEx.txt" ));
}
}
This is my project structure
-project
-ReadTest.java
-dataEx.txt
Working directory
Your path is wrong, thus the reader can not find the file. Whereever you think your current working directory should be, that is not where it is.
Execute the following code to know where it is:
System.out.println(Paths.get("").toAbsolutePath());
That is the path to your current working directory. Then compare that result to your expectation. Realize that your expectation was wrong and correct the path to your file or your working directory settings.
It is hard to guess where your directory might be right now. Maybe in your bin folder, next to the .class files. You will see after executing the above code snippet.
NIO
By the way, not sure what exactly you plan on doing with that BufferedReader but you might be interested in the newer modern file API revolving around Files and Paths:
List<String> lines = Files.readAllLines(Paths.get("myFile.txt"));
It also has other neat utility methods for File IO, much better than the cumbersome File class and the clunky BufferedReader.
I am a real beginner at Java programming so I hope I'm not wasting anyone's time. I tried my best to research this but couldn't come up with a solution.
I am following the Lynda video series "Java Essential Training" and it's been very good so far. I am currently learning how to copy the contents of a text file onto a new text file. However, the video shows a alternative method by downloading commons IO from Apache commons and adding the .jar file to the project.
In the video the jar file was added to build path. My version of eclipse seemed to do it automatically as "Referenced Libraries" popped up, and when I tried to add it eclipse said it was already there.
I followed the video exactly. The code looks like this
package com.lynda.files;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
public class Main {
public static void main(String[] args) {
try {
File f1 = new File("loremipsum.txt");
File f2 = new File("target.txt");
FileUtils.copyDirectory(f1, f2);
System.out.println("File copied!");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
When I ran the code I got the message in console
java.io.IOException: Source 'loremipsum.txt' exists but is not a directory
at org.apache.commons.io.FileUtils.copyDirectory(FileUtils.java:1371)
at org.apache.commons.io.FileUtils.copyDirectory(FileUtils.java:1261)
at org.apache.commons.io.FileUtils.copyDirectory(FileUtils.java:1230)
at com.lynda.files.Main.main(Main.java:16)
In the code it says the FileUtils imported but eclipse tells me "The source attachment does not contain the source for file FileUtils.class". I tried to change the attached source but it gave me the error "Could not write to file BlahBlahBlah.classpath (Access is denied)
Hopefully I didn't drone on about something obvious and simple. I thought it best to be as clear as possible in case someone else has a similar problem.
Edit
I feel so stupid. Thank you for your help. I clicked on "copyDirectory" instead of "copyFile". Next time, instead of panicking, googling every line of error and asking people for help, I'll take the time to go through each line and think about what it does. Thanks to all of you for your help and patience.
See (http://commons.apache.org/proper/commons-io/javadocs/api-2.4/org/apache/commons/io/FileUtils.html#copyFile%28java.io.File,%20java.io.File%29)
Use FileUtils.copyFile(f1, f2); instead of FileUtils.copyDirectory(f1, f2);
The source and target File parameters of copyDirectory must be directories, but you are suppling text files.
public static void copyDirectory(File srcDir,File destDir)
throws IOException
Copies a whole directory to a new location preserving the file dates.
This method copies the specified directory and all its child directories and files to the specified destination. The destination is the new location and name of the directory.
The destination directory is created if it does not exist. If the destination directory did exist, then this method merges the source with the destination, with the source taking precedence.
Note: This method tries to preserve the files' last modified date/times using File.setLastModified(long), however it is not guaranteed that those operations will succeed. If the modification operation fails, no indication is provided.
Parameters:
srcDir - an existing directory to copy, must not be null
destDir - the new directory, must not be null
Throws:
NullPointerException - if source or destination is null
IOException - if source or destination is invalid
IOException - if an IO error occurs during copying
Since:
1.1
(Source)
I found this that may be of help to you:
copyFile(File srcFile, File destFile) Copies a file to a new location preserving the file date.
static void copyFile(File srcFile, File destFile, boolean preserveFileDate) Copies a file to a new location.
static long copyFile(File input, OutputStream output) Copy bytes from a File to an OutputStream.
static void copyFileToDirectory(File srcFile, File destDir) Copies a file to a directory preserving the file date.
static void copyFileToDirectory(File srcFile, File destDir, boolean preserveFileDate) Copies a file to a directory optionally preserving the file date.
Source
Although it's from the Apache site, it does talk about the Java classes.
Please read the error message again:
Source 'loremipsum.txt' exists but is not a directory
This is not exactly what you wrote in your subject. Indeed the file 'loremipsum.txt' exists but it not a directory. It is regular file. However you try to call FileUtils.copyDirectory() and pass this regular file to this method. But this method is not ready to work with files. It supports directories only. This is exactly what is written in error message.
EDIT
Now the question is why do you call method that definitely for intended for directories with parameters that are definitely files?
by running this...
File file = new File("Highscores.scr");
i keep getting this error, and i really don't know how to get around it.
the file is currently sitting in my source packages with my .java files.
I can quite easily read the file by specifying the path but i intend to run this on multiple computers so i need the file to be portable with the program.
this question isnt about reading the text file but rather specifying its location without using an absolute path .
ive searched for the answer but the answers i get are just "specify the name" and "specify the absolute path".
id post an image to make it more clear but i dont have the 10 rep to do so :/
how do i do this?
cheers.
The best way to do this is to put it in your classpath then getResource()
package com.sandbox;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
public class Sandbox {
public static void main(String[] args) throws URISyntaxException, IOException {
new Sandbox().run();
}
private void run() throws URISyntaxException, IOException {
URL resource = Sandbox.class.getResource("/my.txt");
File file = new File(resource.toURI());
String s = FileUtils.readFileToString(file);
System.out.println(s);
}
}
I'm doing this because I'm assuming you need a File. But if you have an api which takes an InputStream instead, it's probably better to use getResourceAsStream instead.
Notice the path, /my.txt. That means, "get a file named my.txt that is in the root directory of the classpath". I'm sure you can read more about getResource and getResourceAsStream to learn more about how to do this. But the key thing here is that the classpath for the file will be the same for any computer you give the executable to (as long as you don't move the file around in your classpath).
BTW, if you get a null pointer exception on the line that does new File, that means that you haven't specified the correct classpath for the file.
As far as I remember the default directory with be the same as your project folder level. Put the file one level higher.
-Project/
----src/
----test/
-Highscores.scr
If you are building your code on your eclipse then you need to put your Highscores.scr to your project folder. Try that and check.
You can try to run the following sample program to check which is the current directory your program is picking up.
File f = new File(".");
System.out.println("Current Directory is: " + f.getAbsolutePath());