I have a method:
try {
PrintWriter writer = new PrintWriter(new File(getResource("save.txt").toString()));
writer.println("level:" + level);
writer.println("coins:" + coins);
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
And it throws this error:
java.io.FileNotFoundException: file:/Users/lpasfiel/Desktop/Java%20Games/Jumpo/out/production/Jumpo/com/salsagames/jumpo/save.txt (No such file or directory)
at java.io.FileOutputStream.open0(Native Method)
at java.io.FileOutputStream.open(FileOutputStream.java:270)
at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
at java.io.FileOutputStream.<init>(FileOutputStream.java:162)
at java.io.PrintWriter.<init>(PrintWriter.java:263)
at com.salsagames.jumpo.Variables$Methods.save(Variables.java:49)
It says the error is in the line with PrintWriter writer = ... The file definitely exists. (but that shouldn't be a problem, should it?). This method has worked for .pngs in an ImageIcon, so I don't see why it would be any different. Could someone explain why this doesn't work and how to fix it?
Lets look carefully at this line:
java.io.FileNotFoundException: file:/Users/lpasfiel/Desktop/Java%20Games/Jumpo/out/production/Jumpo/com/salsagames/jumpo/save.txt (No such file or directory)
If you look at other examples of FileNotFoundException, you will notice that a typical message looks like this:
java.io.FileNotFoundException: /some/path/to/file.txt (No such file or directory)
or
java.io.FileNotFoundException: dir/file.txt (No such file or directory)
In short, a typical "file not found" message starts with an absolute or relative file pathname. But in your example, the message shows a "file:" URL.
I think that that is the problem. I think that you have created a File using a URL string rather than a pathname. The File constructor doesn't check this1, but when you attempt to instantiate the FileWriter, the OS complains that it cannot find a file with that pathname.
(The clues are that the supposed pathname starts with "file:", and that it also includes a %-escaped space.)
Solution:
Something like one of the following ... depending on what getResource() is returning.
File file = new File(getResource("save.txt").toURI());
PrintWriter writer = new PrintWriter(file);
or
PrintWriter writer = new PrintWriter(getResource("save.txt").openStream());
1 - And it shouldn't. A URL string is actually a syntactically valid pathname. Since a File is allowed to represent a file path that doesn't exist in the file system, there would be no basis for the File constructor to reject a URL string.
As requested, this worked:
try {
PrintWriter writer = new PrintWriter(new File(getResource("save.txt").toURI()));
writer.println("level:" + level);
writer.println("coins:" + coins);
writer.close();
} catch (FileNotFoundException | URISyntaxException e) {
e.printStackTrace();
}
Related
My Code:
XWPFDocument doc = new XWPFDocument(OPCPackage.open(ResourceUtils.getFile("classpath:assets/OPTIONS_" + jubilar1.getJubiLanguage().toUpperCase() + ".docx")));
I have already tried instead of .getFile(), extractJarFileFromURL or resource.getInputStream() but all this does not work. When I package my project and run it as a jar file and it tries to open the following file it always returns the following message.
Error:
java.io.FileNotFoundException: class path resource [assets/OPTIONS_DE.
docx] cannot be resolved to absolute file path because it does not
reside in the file system:
jar:file:/home/tkf6y/IdeaProjects/hrapps/backend/target/backend-3.0.0.jar!/BOOT-INF/classes!/assets/OPTIONS_EN.docx
So yes it was the problem, as you are now using an InputStream as I suggested. The problem was (and always has been) the getFile stuff. What I suggest to do is don't use what you have now but rather do a new ClassPathResource(your location).getInputStream()) instead, it is easier, or even use a ResourceLoader (a Spring interface you can inject) and then use the path you had an again use getInputStream(). –
This works for me.
String strJson = null;
ClassPathResource classPathResource = new ClassPathResource("json/data.json");
try {
byte[] binaryData = FileCopyUtils.copyToByteArray(classPathResource.getInputStream());
strJson = new String(binaryData, StandardCharsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
I'm making a program where I have to make a file and then deserialize the object in that file. When I name the file something, such as "contacts.dat", I get a FileNotFoundException.
The code is below:
public static void main(String[] args) {
String inputstring = Input.getString("Please enter the name of the file containing the contacts: ");
TreeMap< String, Contact > contactlist = null;
ObjectInputStream in;
try {
in = new ObjectInputStream(new BufferedInputStream(new FileInputStream(inputstring)));
contactlist = (TreeMap< String, Contact >) in.readObject();
in.close();
}
catch(ClassNotFoundException | EOFException emptyexcptn) {
System.out.println("The file provided is currently empty.");
contactlist = new TreeMap< String, Contact >();
}
catch(IOException ioexcptn) {
ioexcptn.printStackTrace(System.out);
System.out.println("Error reading file: " + inputstring);
System.exit(1);
}
Here's what the exception prints:
java.io.FileNotFoundException: contacts.dat (The system cannot find the file specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.(FileInputStream.java:138)
at java.io.FileInputStream.(FileInputStream.java:93)
at UnitEight.AssignmentEight.main(AssignmentEight.java:16)
Error reading file: contacts.dat
Your argument to new FileInputStream() is String inputstring = Input.getString("Please enter the name of the file containing the contacts: ");...if Input.getString returns the path for the file then you are pointing to the wrong path anyway.
Print the result of Input.getString()...if any and that would give you a clue what's going on there.
From the API docs -
Constructor Detail
FileInputStream
public FileInputStream(String name) throws FileNotFoundException
Creates a FileInputStream by opening a connection to an actual file, the file named by the path name name in the file system. A new FileDescriptor object is created to represent this file connection.
First, if there is a security manager, its checkRead method is called with the name argument as its argument.
If the named file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading then a FileNotFoundException is thrown.
Parameters:name - the system-dependent file name.Throws:FileNotFoundException - if the file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading.SecurityException - if a security manager exists and itscheckRead method denies read access to the file.
To summarize in to a working example:
When you are using the FileInputStream(String filename), try it by specifying the full (absolute) path to the file so your program can find it. Ex: if your text.dat file was on a shared drive Z: your String you would have to pass as a parameter to the constructor would be
"Z:\\text.dat" instead of using an OS specific slash character it is better to use File.separator in the above example it would look like "Z" + File.separator + "text.dat".
if (!file.exists())
file.mkdirs();
file.createNewFile();
The error states that I have a problem with actually 'writing' Go Falcons to the file, it will state that the file access is denied, Does that mean something is wrong with my code?
Error states: FileNotFoundException
Access is denied
PS: how do I actually read this file, once it's writable?
If I understand your question, one approach would be to use a PrintWriter
public static void main(String[] args) {
File outFile = new File(System.getenv("HOME") // <-- or "C:/" for Windows.
+ "/hello.txt");
try {
PrintWriter pw = new PrintWriter(outFile);
pw.println("Go Falcons");
pw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Which creates a single line ascii file in my home folder named "hello.txt".
$ cat hello.txt
Go Falcons
Your problem is that right before you attempt to create your output file, you first create a directory with the same name:
if (!file.exists())
file.mkdirs(); // creates a new directory
file.createNewFile(); // fails to create a new file
Once you've already created the directory, you can no longer create the file, and of course, you cannot open a directory and write data to it as if it were a file, so you get an access denied error.
Just delete the file.mkdirs(); line and your code will work fine:
if (!file.exists())
file.createNewFile(); // creates a new file
Change:
if (!file.exists())
file.mkdirs();
file.createNewFile();
To:
if (!file.exists()) {
file.createNewFile();
}
But first, go read some tutorials or articles. Why are you extending Exception?
You can take the substring of the path till folder structure(excluding file name) and create directories using method mkdirs(). Then create file using createNewFile() method. After that write to newly created file. Don't forget to handle exceptions.
File file1 = new File(file.getAbsoluteFile() + "/example/directory/example.png");
file1.mkdirs();
file1.setWritable(true);
file1.createNewFile();
try {
FileInputStream is = new FileInputStream(exampleInputDirectory);
FileOutputStream os = new FileOutputStream(file1);
FileChannel srcChannel = is.getChannel();
FileChannel dstChannel = os.getChannel();
dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
is.close();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
This is my setup for copying an image file to a new directory tree. However, when this code is executed I get the following:
java.io.FileNotFoundException: *points to output directory* (Access is denied)
Have I gone about creating file1 incorrectly?
The problem here is because of using
file1.mkdirs();
and
file1.createNewFile();
together.
Since the file1 object is already been given 'directory' attributes after creating it as directory by calling "file1.mkdirs()", but then you are again using the same object to create a 'file', that means changin attribute of file1 object from directory to a file, which is not allowed. that's why its giving you FileNotFound.
Your creation of file1 seems to be up to par, maybe your input dir is non existent? Make sure all caps and such are correct, and that there are no typos in your directory reference. Also be sure if the user has permissions to copy a file to the directory, if not you can run it as root in linux, and as administrative in windows.
I am trying to write some message to text file. The text file is in the server path. I am able to read content from that file. But i am unable to write content to that file. I am getting FileNotFoundException: \wastServer\apps\LogPath\message.txt (Access Denied).
Note: File has a read and write permissions.
But where i am doing wrong. Please find my code below.
Code:
String FilePath = "\\\\wastServer\\apps\\LogPath\\message.txt";
try {
File fo = new File(FilePath);
FileWriter fw=new FileWriter(fo);
BufferedWriter bw=new BufferedWriter(fw);
bw.write("Hello World");
bw.flush();
bw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Please help me on this?
Please check whether you can access the apps and LogPath directory.
Type these on Run (Windows Key + R)
\\\\wastServer\\apps\\
\\\\wastServer\\apps\\LogPath\\
And see whether you can access those directories from the machine and user you are executing the above code.
You don't have write access to the share, one of the directories, or the file itself. Possibly the file is already open.
After this line
File fo = new File(FilePath);
try to print the absolute path
System.out.println( fo.getAbsolutePath() );
And then check whether the file exists in that location, instead of directly checking at
\\\\wastServer\\apps\\LogPath\\message.txt
So , you will know, where the compiler is searching for the file.