Cant figure out Java find for an "abstract path" - java

I am working in eclipse trying to create a file.
This is my code:
File file = new File("C:\Users\Local Admin\Desktop\1.txt");
I copied the path I am using directly from the properties of the file but I keep getting the error
Invalid escape sequences.
I tried adding an extra "\" in front of each "\" but that didn't fix anything.
Any suggestions?

It should be either:
File file = new File("C:\\Users\\Local Admin\\Desktop\\1.txt");
Or:
File file = new File("C:/Users/Local Admin/Desktop/1.txt");

Replace "\" by either "\\" or "/".
Try this.
File file=new File("C:/Java/hello.txt");

Try storing the path of the file in a string variable and passing that string variable.Use "\\" if "\" doesn't works.
String filePath="your path";
File file=new File(filePath);

Related

How to get path to package in Eclipse (Java)

I'm currently reading a txt file in Java, which is located in a package with the scanner object.
To receive the file location I use a quick and dirty method:
File currentDirectory = new File(new File(".").getAbsolutePath());
String location = currentDirectory.getAbsolutePath().replace(".", "")+"\\corefiles\\src\\filereadingexample\\";
Is there a better way of doing so?
I'd love to improve my code.
Greetings
J
Use a URL
URL resource = getClass().getResource("/path/to/text/file.txt");
As the path, since your text file is inside a package, use the package structure. For example, assume your file(myfile.txt) is inside
com.myproject.files
package, your path should be
"/com/myproject/files/myfile.txt"
(mind the leading slash. It's necessary)
Now you can create a File using the URL
new File(resource.getFile());
The "resource.getFile()" returns the absolute path to the file also.
Hope this helps
Get current diretory path
String currentDirPath = System.getProperty("user.dir");
String ohterPackages = currentDirPath + File.separator + "filereadingexample\\fileName.txt";
User home directory
String homePath = System.getProperty("user.home");

Create directory at given path in Java - Path with space

I have my java code like below-
string folderName = "d:\my folder path\ActualFolderName";
File folder = new File( folderName );
folder.mkdirs();
So here as given directory path has space in it. folder created is d:\my, not the one I am expecting.
Is there any special way to handle space in file/folder paths.
You should us \\ for path in java. Try this code
String folderName = "D:\\my folder path\\ActualFolderName";
File folder = new File( folderName );
folder.mkdirs();
Or use front-slashes / so your application will be OS independent.
String folderName = "D:/my folder path1/ActualFolderName";
Unless you are running a really old version of Java, use the Path API from JDK7:
Path p = Paths.get("d:", "my folder path", "ActualFolderName");
File f = p.toFile();
It will take care of file separators and spaces for you automatically, regardless of OS.
Following alternatives should work in Windows:
String folderName = "d:\\my\\ folder\\ path\\ActualFolderName";
String folderName = "\"d:\\my folder path\\ActualFolderName\"";
You need to escape your path (use \\ in your path instead of \) and you also need to use String, with an uppercase S, as the code you posted does not compile. Try this instead, which should work:
String folderName = "D:\\my folder path\\ActualFolderName";
new File(folderName).mkdirs();
If you are getting your folder name from user input (ie.not hardcoded in your code), you don't need to escape, but you should ensure that it is really what you expect it is (print it out in your code before creating the File to verify).
If your are still having problems, you might want to try using the system file separator character, which you can get with System.getProperty(file.separator) or accesing the equivalent field in the File class. Also check this question.
You need to escape path seprator:
String folderName = "D:\\my folder path\\ActualFolderName";
File file = new File(folderName);
if (!file.exists()) {
file.mkdirs();
}
First of all, the String path you have is incorrect anyway as the backslash must be escaped with another backslash, otherwise \m is interpreted as a special character.
How about using a file URI?
String folderName = "d:\\my folder path\\ActualFolderName";
URI folderUri = new URI("file:///" + folderName.replaceAll(" ", "%20"));
File folder = new File(folderUri);
folder.mkdirs();

java File.separator becomes "%" in path of the File on Windows

I try to read files from the resources folder. The problem is, that the File.separator turns into a "%" on Windows.
String inputFilesFolder = "input_files" + File.separator;
File file = new File(classLoader.getResource(inputFilesFolder + "filename").getFile());
The inputFilesFolder is still fine (input_files/), but after creating the file file.getPath() becomes D:\blabla\input_files%filename.
Then I try to read the file, but I get a FileNotFoundException (big surprise).
What's wrong here?
File.separator is a file system thing. When you're using classLoader.getResource() always use forward slash as the name of a resource is a '/'-separated path name.
See Javadoc for getResource()
Try this:
File file = new File(classLoader.getResource(inputFilesFolder + filename).toURI());
How about
String inputFilesFolder = "input_files" + File.separator;
File file = new File(classLoader.getResource(inputFilesFolder + filename).toString());

Get the filePath from Filename using Java

Is there a easy way to get the filePath provided I know the Filename?
You can use the Path api:
Path p = Paths.get(yourFileNameUri);
Path folder = p.getParent();
Look at the methods in the java.io.File class:
File file = new File("yourfileName");
String path = file.getAbsolutePath();
I'm not sure I understand you completely, but if you wish to get the absolute file path provided that you know the relative file name, you can always do this:
System.out.println("File path: " + new File("Your file name").getAbsolutePath());
The File class has several more methods you might find useful.
Correct solution with "File" class to get the directory - the "path" of the file:
String path = new File("C:\\Temp\\your directory\\yourfile.txt").getParent();
which will return:
path = "C:\\Temp\\your directory"
You may use:
FileSystems.getDefault().getPath(new String()).toAbsolutePath();
or
FileSystems.getDefault().getPath(new String("./")).toAbsolutePath().getParent()
This will give you the root folder path without using the name of the file. You can then drill down to where you want to go.
Example: /src/main/java...

Java: How to create a new folder in Mac OS X

I want to create a folder in ex. my desktop in Mac OS X
I try to use this code, instead of Mymac is my name of course:)
String path="/Users/Mymac/Desktop";
String house = "My_home";
File file=new File(path);
if(!file.exists())
file.mkdirs(); // or file.mkdir()
file=new File(path + "/" + house);
try {
if(file.createNewFile())
{
}
} catch (IOException ex) {
ex.printStackTrace();
}
Do you know how I could create a new folder?
And another thing is when I want to create a folder in the directory where my code is, do you know how I could write that? I have tried
String path="./";
String path="::MyVolume";
String path=".";
A platform-independent way:
File rootDir = File.listRoots()[0];
File dir = new File(new File(new File(rootDir, "Users"), "Mymac"), "Desktop");
if (!dir.exists()){
dir.mkdirs();
}
Your code is ok and will work. Perhaps you have a typo in your username in your file-path ("Mymac"), so you don't see the changes, since they go to another folder.
Running this code on my machine works fine and gives the expected result.
To make your code platform-independant, you can build your file-path with the following trick:
File path = new File(File.listRoots()[0], "Users" + System.getProperty("file.separator") + "Mymac" + System.getProperty("file.separator") + "Desktop"));
If "My_home" should be a folder and not a file, you have to change the file.createNewFile() - command. More detailed information you'll find in the answer of Thomas.
To find the folder/directory where one of your classes is (assuming they are not in a Jar), and then to create a subfolder there:
String resource = MyClass.class.getName().replace(".", File.separator) + ".class";
URL fileURL = ClassLoader.getSystemClassLoader().getResource(resource);
String path = new File(fileURL.toURI()).getParent();
String mySubFolder = "subFolder";
File newDir = new File(path + File.separator + mySubFolder);
boolean success = newDir.mkdir();
(The code above could be made more compact, I listed it more verbosely to demonstrate all the steps.) Of course, you need to be concerned about permission issues. Make sure that the user which is running java has permission to create a new folder.
Use file.mkdir() or file.mkdirs() instead of file.createNewFile() and it should work, if you have permission to create new folders and files.
mkdirs() will create the subfolders if they don't exist, mkdir() won't.
To create a directory in your base directory (the one you start your application from), just provide a relative path name: new File("mydir").mkdir();
Edit: to make file handling easier, I'd suggest you also have a look at Apache Commons' FilenameUtils and FileUtils.

Categories