Reputation: 1
I'm using Windows7. I've written this simple java code:
package filetest;
import java.io.File;
public class FileTest {
public static void main(String[] args) {
File myfile = new File("C://test//test.txt");
if (myfile.exists()) {
System.out.println("file exists");
} else {
System.out.println("file doesn't exist");
}
}
}
The file DOES exists in C:/test/test.txt, but the answer is that file doesn't exists. Why?
EDITED: I've changed the code and it still doesn't find the file, but now it creates the file. So I can write to that directory. And the created file is named "test"
package filetest;
import java.io.File;
import java.util.*;
public class FileTest {
public static void main(String[] args) {
File myfile = new File("C:\\test\\test.txt");
final Formatter newfile;
if (myfile.exists()) {
System.out.println("file exists");
} else {
System.out.println("file doesn't exist");
try {
newfile = new Formatter("C://test//test.txt");
System.out.println("file has been created");
} catch(Exception e) {
System.out.println("Error: " + e);
}
}
}
}
Upvotes: 0
Views: 972
Reputation: 476
@SSorensen In your EDITED code, you added the backslash properly
@ line 7
File myfile = new File("C:\\test\\test.txt");
but you forgot to update slashes with backslashes @ line 14
newfile = new Formatter("C://test//test.txt");
Upvotes: 0
Reputation: 58
I would recommend using isFile() instead of exists(). Its a better way of checking if the path points to a file rather than if a file exists or not. exists() may return true if your path points to a directory.
Upvotes: 1
Reputation: 25950
You don't need to double your slashes. You have to user wether "/"
or "\\"
.
EDIT :
The weird thing is that I tried it out and both "/"
and "\\"
work fine for me. In fact, it works regardless of the number of "/" I use... for example "C:////test/////////test.txt"
is okay. You have another problem, and I have no idea of what it could be.
Upvotes: 1
Reputation: 1319
In windows path separator used is '\' for these you need to escape backslash.So your code will be something like:
public class FileTest {
public static void main(String[] args) {
File myfile = new File("C:\\test\\test.txt");
if (myfile.exists()) {
System.out.println("file exists");
} else {
System.out.println("file doesn't exist");
}
}
}
Upvotes: 1