I am attempting to access a file within my current working directory.
The error I am getting is
[java] java.io.FileNotFoundException: /u/user/Documents/DataComProject1\confA.txt
The line which is causing this, I presume is:
bufferedReader = new BufferedReader(new FileReader(System.getProperty("user.dir") + "/" + fileName));
Whenever I print the directory I'm attempting to use with FileReader() I get:
/u/user/Documents/DataComProject1/confA.txt
I believe the problem has to do with the the backslash before the text file name being in a different direction. Upon looking in the directory I can see the file is there.
You could use the Path library instead of creating the path yourself:
Path p = Paths.get(System.getProperty("user.dir"))
.resolve(filename);
File f = p.toFile();
Don't write "/" to separate path elements, use this instead to get the correct path separator that's appropriate for your platform:
File.separator
It looks like your fileName includes an embedded backslash: it's Documents/DataComProject1\confA.txt. Since the backslash is a valid character in a file name, DataComProject1\confA.txt is assumed to be name of the file, not a name of a file in a directory.
To fix the file name you have to change the embedded \\ into the correct separator character:
fileName = fileName.replace('\\', File.separator);
bufferedReader = new BufferedReader(new FileReader(System.getProperty("user.dir") + "/" + fileName));
It would be correct to use the slash / as the directory separator on every system, but here I use File.separator because not using a hardcoded value makes the intent of the code clearer.
Related
I am working in Netbeans IDE.
What I want to do is:
Get The directory of the Current Java Application (Ex: "F:\PadhooWorld")
Join a file name to it. (Ex: "\Somestuff.txt")
Check if that File exists (Ex: "F:\PadhooWorld\Somestuff.txt")
Do a if.. else activity
When I tam trying to Join Directory + Filename, it is throwing lots of error messages like Path cannot be converted to string etc . Searching the net the whole day, doesn't yield any simple usable solution
Please specify a very simple solution.
EDIT
I have only 2 lines of code as yet
String AppPath = System.getProperty("user.dir");
String fullPath = AppPath + "\Surabhi.txt";
The First Line resolves alright
The Second line (I tried different variations) No Luck. It is underlined in red. Error hints say stuffs like 'Path cannot be converted to string'..
I cannot RUN the code.
It sounds like you're overthinking it. You can just create a File object with the file name you want (the path to the current directory will be used by default) and then call exists() on it:
File f = new File("filename.txt");
System.out.println(f.getAbsolutePath()); //Just for debug if you want to check the path
if(f.exists()) {
//Whatever
}
Alternatively, if you want to specify the path as well as the file name:
String AppPath = System.getProperty("user.dir");
String fileName = "Surabhi.txt";
File f = new File(AppPath, fileName); //f.getAbsolutePath() will give the concatenated name
if(f.exists()) {
//Whatever
}
I am trying to output an object to a file, and the code below works fine.
val myFile = new File(myPath + "_" + myFileName)
val myData = new ObjectOutputStream(new FileOutputStream(myFile))
However, if I want to make myFileName under myPath like:
val myFile = new File(myPath + "/" + myFileName)
val myData = new ObjectOutputStream(new FileOutputStream(myFile))
I got java.io.FileNotFoundException.
Any idea what I might have missed? Thank you!
If folder myPath does not exists the FileNotFoundException will be thrown. You have to create that folder first. You may do it manually or by mkdir() method from File class.
This error is definitely due to missing folder referenced by "mypath" or myFileName.
JDK7 has nice abstraction for path in which you don't have to worry about path separator character (i.e /)
Use Paths
for eg
Path p = Paths.get("c:", myPath ,myFileName)
You can extract file object from path and do whether path exists before starting any processing.
I'm trying to get to some text file in my computer but I keep getting this exception although the path is correct and the file is exist.
Here is my code:
public static void main(String[] args) throws IOException {
File wordFile = new File("D:\\IDC\\Stuff\\wordList.txt");
RandomAccessFile wordsList = new RandomAccessFile(wordFile, "rw");
System.out.println(wordFile.exists());
}
The error:
Exception in thread "main" java.io.FileNotFoundException: D:\IDC\Stuff\wordList.txt (The filename, directory name, or volume label syntax is incorrect)
at java.io.RandomAccessFile.open(Native Method)
at java.io.RandomAccessFile.<init>(RandomAccessFile.java:243)
at WordChecker.main(WordChecker.java:12)
When I copied your code and tried to save it in Eclipse. I got the below error
I concluded from this, although your path looks 'D:\\IDC\\Stuff\\wordList.txt' but actually it is not.So what I did, just type this line File file =new File("D:\\IDC\\Stuff\\wordList.txt"); instead of copy it from your code. And it worked. It seems you also copied it from somewhere and for encoding issue you are getting the problem.
One more point, you should use System.getProperty("file.separator") instead of \\ or / just like below
File wordFile = new File("D:" + System.getProperty("file.separator")
+ "IDC" + System.getProperty("file.separator") + "Stuff"
+ System.getProperty("file.separator") + "wordList.txt");
file.separator
Character that separates components of a file path. This is "/" on UNIX and "\" on Windows.
Can you rename the file? This can help if you copied the file name from another location and it had non-visible characters in it.
I am having trouble accessing a file within my Jar on Windows. I do not have this problem when I run it on Unix. I have created the jar both on Windows & Unix and it makes no difference. Either way it does not run on Windows.
I ran the jar -tf command on my jar and the class I am running from is located in: a/b/c/d/ClassOne.class. The class I am looking for is located in my base directory of the jar: ClassTwo.class
My code in this ClassOne looks like the following:
String path = File.separator + "myYAML.yml";
InputStream in = MetricCollector.class.getResourceAsStream(path);
InputStreamReader isr = new InputStreamReader(in);
BufferedReader input = new BufferedReader(isr);
My code breaks on the last line shown throwing a NullPointerException which I can only believe means it cannot find the path I have given it. However, this exact code works great on my debugger and on Unix when I run the jar.
I have also tested the following paths:
"myYAML.yml"
File.seperator + ".." + File.seperator + ".." + File.seperator + ".." + File.seperator + ".." + "myYAML.yml"
".." + File.seperator + ".." + File.seperator + ".." + File.seperator + ".." + "myYAML.yml"
all to no avail.
I have used the following Stack Overflow posts to get as far as I can, but they do not seem to have an answer for me: How to reference a resource file correctly for JAR and Debugging?, Accessing resources within a JAR file and Reading file from within JAR not working on windows
Any additional help I would be extremely grateful for. Thanks in advance.
File.separator cannot work on Windows, it returns \. You need to use / as a separator regardless of the OS.
The Class#getResource(String) states
Before delegation, an absolute resource name is constructed from the
given resource name using this algorithm:
If the name begins with a '/' ('\u002f'), then the absolute name of
the resource is the portion of the name following the '/'. Otherwise,
the absolute name is of the following form: modified_package_name/name
Where the modified_package_name is the package name of this object
with '/' substituted for '.' ('\u002e').
In other words, you must use /. This is further explained in the javadoc for ClassLoader.html#getResource(java.lang.String) to which Class#getResource delegates.
The name of a resource is a /-separated path name that identifies the
resource.
If the resource is at the root of the classpath, use
InputStream in = MetricCollector.class.getResourceAsStream("/myYAML.yml");
I'm trying to list a directory's contents, and rename certain files.
public void run(String dirName) {
try {
File parDir = new File(dirName);
File[] dirContents = parDir.listFiles();
// Rename if necessary
for(File f : dirContents) {
System.out.println("f is:\n" + f.toString());
String name = f.getName();
String subbedName = name.replaceAll("\uFFFD", "_");
System.out.println("\n" + "name = " + name + ", subbedName = " + subbedName + "\n");
if(!name.equals(subbedName)) {
File newFile = new File(f.getParentFile(), subbedName);
System.out.println("newFile is:\n" + newFile.toString());
if(!f.renameTo(newFile))
System.out.println("Tried to change file name but couldn't.");
}
}
}
catch(Exception exc1) {
System.out.println("Something happened while listing and renaming directory contents: " + exc1.getMessage());
}
}
When I run this, I get "Tried to change file name but couldn't." I don't believe that Java is considering these files to be "open", so I don't think that's the reason. I've even ran chmod 777 myDir where myDir is the value of the dirName string passed into the run method.
What am I missing here? Why won't Java rename these file(s)? These are CentOS machines.
Edit: Added printouts for both f and newFile, which is as follows:
f is:
/root/path/to/mydir/test�.txt
newFile is:
/root/path/to/mydir/test_.txt
You need to create your new File object with the full pathname of those files. So
String name = f.getName(); // gets the name without the directory
should likely be:
String name = f.getAbsolutePath();
(your search/replace may need to change)
The problem is that f.getName() returns the last name component of the path that is represented by f. You then massage this String and turn it back into a File. But the File now represents a path relative to the current directory, not the directory containing the original path.
As a result your code is actually attempting to rename the files from dirName into the application's current directory. That could fail because files already exist in the current directory with those names, or because the dirName and the current directory are in different file systems. (You cannot rename a file from one filesystem to another ... you have to copy it.)
Please note that a File in Java represents a pathname, not a file or a folder. In your code, the f objects are the pathnames for file system objects (either files or folders) in the directory denoted by the String dirname. Each of these f objects will have a directory part.
There is more than one way to fix your code; for example
change name = f.getName() to name = f.toString()
change new File(subbedName) to new File(f.getParentFile(), subbedName)
I have an alternative / additional theory.
The pathname of the file containing the \uFFFD character is coming out as "mojibake"; i.e. the kind of garbled text that you get when you display encoded text using the wrong encoding. And since we are seeing 3 characters of garbled text, I suspect that it is attempting to display the UTF-8 rendering of \uFFFD as Latin-1.
So my theory is that the same think is happening when the File.renameTo method is converting f to the form that it is going to provide to the system call. For some reason that is no clear to me, Java could be using the wrong encoding, and as a result producing a "name" for the original file that doesn't match the name of the file in the file system. That would be sufficient to cause the rename to fail.
Possibly related questions / links:
File name charset problem in java
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4733494 (Note that Sun decided this was not a Java bug, and most of the "me too" comments on the bug report are from people who do not understand the explanation ...)
f.getName(); only returns the name of the folder, not the full path. So subbedName becomes a relative path file. Try something with f.getCanonicalPath() instead.