There are a lot of topics on this problem, but not one seems to have the answer I am looking for. I am attempting to open a file for read/write, but I get the file not found exception. I specified the absolute path, but to no avail. When I check "exists" and "canread" both return false. I have tried multiple files, and the result is always false. Someone mentioned it could be a permission issue, but I don't know how to fix that. Once more, if "exists" returns false, I doubt its just permission issues. Any help would be appreciated.
File myfile = new File("C:\\Users\\Eric\\workspace\\ReadJPG\\test.txt");
//File myfile = new File("C:/Users/Eric/workspace/ReadJPG/test.txt");
boolean h = myfile.canRead();
boolean p = myfile.exists();
try {
FileInputStream fis = new FileInputStream(myfile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Check the path. The format you're using works. I tried to replicate, but could only by miswriting the file name. My code:
import java.io.File;
public class Main {
public static void main(String[] args) {
File myfile = new File("C:\\Users\\iajrz\\Desktop\\usepass.txt");
System.out.println(myfile.exists());
}
}
prints true. Even if you had permission issues, "exists()" should return true if the file exists. Permissions wouldn't let you read, or write; they wouldn't forbid you from knowing that the file exists (i.e. listing). I tried.
Related
The way I go is
Resource iconHomeResource = new ClassPathResource("/assets/icons/icons8-home-16.png");
//print iconHomeResource.exists() IS TRUE
File iconHome = iconHomeResource.getFile() //throws FileNotFoundException.
In the past I used something like this.
/** This Work inside IDE but not in production*/
public File loadEmployeesWithSpringInternalClass()
throws FileNotFoundException {
return ResourceUtils.getFile(
"classpath:data/employees.dat");
}
I read some similiar Questions/Answeres here on SoF but not of them worked for me.
Files inside the (Tracks)directory was not deleted. The method deletes the wav files stored in the directory.
public boolean deleteTrack(response) {
ListIterator<Track> trackListIterator = this.trackList.listIterator();
//tracklist is the linked list on which I'm using list iterator. I'm storing song which is a object inside it. this object has a fn() that returns content root path not absolute path.
String path = "";
while (trackListIterator.hasNext()) {
//RESPONSE == PARAMETER
if (trackListIterator.next().getTrackName().equals(response)) {
trackListIterator.previous();
path = trackListIterator.next().getTrackPath();//this is the fn() that
returns content root path example(src/Exploit/org/Trackstore/Music/Action Movie Music-FesliyanStudios.wav).
break;
}
}
File file = new File(path);
//here I'm taking absolute path for deleting actual wav file from the computer.
File toBeDeleted = new File(file.getAbsolutePath());
return toBeDeleted.delete();// returns false everytime.
}
The old API has many issues. For example, most methods return a boolean to indicate the result which is stupid and unjavalike - fortunately, there is a new API that fixes these issues.
Use it and you'll know WHY it failed. If that's too much effort, well, there isn't much to say. It didn't delete. No idea why, and there's no way to ask that API about why.
The new API lives in the java.nio.file package.
Replace this:
File f = new File("path/to/file");
if (!f.delete()) { ... it didn't work ... }
with:
Path p = Paths.get("path/to/file");
try {
Files.delete(p);
} catch (IOException e) {
// the exception will explain everything there is to be said about why it did not work!
}
bellow is the code of a house cleaning function i have written, the function is supposed to check for a files existance, if it is not there it then creates the file and adds some data to it.
However when i check that i have read and write permisions using the file.canRead() and file.canWrite() these both return false when checked however the program should have access to the file path where specified.
public void HouseCleaning()
{
//inform the user that the file is not available
System.out.println("According the the checks we have run, the current system you are on we do not have the required files set up");
System.out.println("...");
//create info.txt
try
{
File file = new File("C:\\GameCounter\\info.txt");
System.out.println(file.canRead());
System.out.println(file.canWrite());
if(file.canRead() && file.canWrite())
{
//then we can create the file
System.out.println("we can do this");
if(!file.exists())
{
//file does not exist
if(file.createNewFile())
{
//file has been created
System.out.println("File has been successfully created!");
PrintWriter writer = new PrintWriter("C:\\GameCounter\\info.txt", "UTF-8");
writer.println("Info File:");
writer.flush();
writer.close();
}
else
{
//file has not been created!
System.out.println("for some reason the file cannot be created!");
}
}
else
{
//file must already exist? so check for other required ones!
}
}
else
{
System.out.println("we require extre permissions!");
}
}
catch(Exception e)
{
//error has been thrown
System.out.println(e);
}
}
So my question is firstly is that theoretically if the code bellow is correct then it is permissions on the hard disk itself then? if the code is not correct please do correct me.
Many Thanks for any help regarding this.
I suggest you change your program and use the advantages Javas Exception Handling has to offer.
private final static String COUNTER = "C:\\GameCounter\\info.txt";
public static void main(String[] args) {
File file = new File(COUNTER);
if (!file.exists()) {
try {
PrintWriter writer = new PrintWriter(COUNTER, "UTF-8");
writer.println("Info File:");
writer.flush();
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
/// ... more to come
}
This is a lot shorter and you have to take care of the exceptions anyway. If the file can not be written to (In my test I simply created it and assigned the readonly attribute) you will receive an according exception:
java.io.FileNotFoundException: C:\GameCounter\info.txt (Access denied)
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:192)
at java.io.PrintWriter.<init>(PrintWriter.java:232)
at xyz.main(xyz.java:12)
In my example I only dump the exception to the screen. In a real life scenario you need to react on the exception and perhaps re-throw a exception you defined on your own.
The methods canRead and canWrite return false if the file does not exist.
Quote from the documentation (canRead):
Returns:
true if and only if the file specified by this abstract pathname exists and can be read by the application; false otherwise
and (canWrite):
Returns:
true if and only if the file system actually contains a file denoted by this abstract pathname and the application is allowed to write to the file; false otherwise.
The reason the file.canRead() file.canWrite() return false are most likely because you have not created the files.
Java Doc
public boolean canRead() Tests whether the application can
read the file denoted by this abstract pathname.
The method calls return true when you create the files first.
Remember, File is a representation of a system file, simply creating an instance of the File object will not create a file
The following program has the purpose of creating a directory,
folderforallofmyjavafiles.mkdir();
and making a file to go inside that directory,
File myfile = new File("C:\\Users\\username\\Desktop\\folderforallofmyjavafiles\\test.txt");
There are two problems though. One is that it says the directory is being created at the desktop, but when checking for the directory, it is not there. Also, when creating the file, I get the exception
ERROR: java.io.FileNotFoundException: folderforallofmyjavafiles\test.txt (The system cannot find the path specified)
Please help me resolve these issues, here is the full code:
package mypackage;
import java.io.*;
public class Createwriteaddopenread {
public static void main(String[] args) {
File folderforallofmyjavafiles = new File("C:\\Users\\username\\Desktop");
try {
folderforallofmyjavafiles.mkdir(); //Creates a directory (mkdirs makes a directory)
if (folderforallofmyjavafiles.isDirectory() == true) {
System.out.println("Folder created at " + "'" + folderforallofmyjavafiles.getPath() + "'");
}
} catch (Exception e) {
System.out.println("Not working...?");
}
File myfile = new File("C:\\Users\\username\\Desktop\\folderforallofmyjavafiles\\test.txt");
//I even tried this:
//File myfile = new File("folderforallofmyjavafiles/test.txt");
//write your name and age through the file
try {
PrintWriter output = new PrintWriter(myfile); //Going to write to myfile
//This may throw an exception, so I always need a try catch when writing to a file
output.println("myname");
output.println("myage");
output.close();
System.out.println("File created");
} catch (IOException e) {
System.out.printf("ERROR: %s\n", e); //e is the IOException
}
}
}
Thank you so much for helping me out, I really appreciate it.
:)
You're creating the Desktop folder in the C:\Users\username folder. If you check the return value of mkdir, you'd notice it's false because the folder already exists.
How would the system know that you want a folder named folderforallofmyjavafiles unless you tell it so?
So, you didn't create the folder, and then you try to create a file in the (nonexistent) folder, and Java tells you the folder doesn't exist.
Agreed that it's a bit obscure, using a FileNotFoundException, but the text does say "The system cannot find the path specified".
Update
You're probably confused about the variable name, so let me say this. The following are all the same:
File folderforallofmyjavafiles = new File("C:\\Users\\username\\Desktop");
folderforallofmyjavafiles.mkdir();
File x = new File("C:\\Users\\username\\Desktop");
x.mkdir();
File folderToCreate = new File("C:\\Users\\username\\Desktop");
folderToCreate.mkdir();
File gobbledygook = new File("C:\\Users\\username\\Desktop");
gobbledygook.mkdir();
new File("C:\\Users\\username\\Desktop").mkdir();
I'll post my code first:
private void validateXml(String xml) throws BadSyntaxException{
File xmlFile = new File(xml);
try {
JaxbCommon.unmarshalFile(xml, Gen.class);
} catch (JAXBException jxe) {
logger.error("JAXBException loading " + xml);
String xmlPath = xmlFile.getAbsolutePath();
System.out.println(xmlFile.delete()); // prints false, meaning cannot be deleted
xmlFile.delete();
throw new BadSyntaxException(xmlPath + "/package.xml");
} catch (FileNotFoundException fne) {
logger.error("FileNotFoundException loading " + xml + " not found");
fne.printStackTrace();
}
}
You can see in my comment where I print that the file cannot be deleted. Files can't be deleted from a try/catch? So, if there is a file with bad xml syntax, I want to delete the file in the catch.
EDIT: I can delete the file when I use delete() from outside of this function. I am on Windows.
Make sure that this method invocation JaxbCommon.unmarshalFile(xml, Gen.class); closes any stream when the exception occurs. If the stream that was reading the file is left opened then you cannot delete it.
The problem is unrelated to the try/catch. Do you have permissions to delete the file?
If you are using Java 7 you can use the Files.delete(Path) which I think will actually throw an IOException with the reason why you can't delete the file.
There is no general restriction regarding the use of java.io.File.delete() on try/catch blocks.
The behavior of many java.io.File methods can depend on platform/enviroment that the application is running. It is because they can need to access file system resources.
For example, the following code returns false on Windows 7 and true on Ubuntu 12.04:
public static void main(String[] args) throws Exception {
File fileToBeDeleted = new File("test.txt");
// just creates a simple file on the file system
PrintWriter fout = new PrintWriter(fileToBeDeleted);
fout.println("Hello");
fout.close();
// opens the created file and does not close it
BufferedReader fin = new BufferedReader(new FileReader(fileToBeDeleted));
fin.read();
// try to delete the file
System.out.println(fileToBeDeleted.delete());
fin.close();
}
So, the real problem can depend on several factors. However, it is not related to the code residing on a try/catch block.
Maybe, the resource that you is trying to delete was opened and not closed or locked by another process.