How to get absolute path from FileDialog? - java

I'm creating FileDialog and trying to get a FilePath for FileDialog object.
FileDialog fd = new FileDialog(this, "Open", FileDialog.LOAD);
fd.setVisible(true);
String path = ?;
File f = new File(path);
In this codes, I need to get a absolute FilePath for using with File object.
How can I get filepath in this situation?

You can combine FileDialog.getDirectory() with FileDialog.getFile() to get a full path.
String path = fd.getDirectory() + fd.getFile();
File f = new File(path);
I needed to use the above instead of a call to File.getAbsolutePath() since getAbsolutePath() was returning the path of the current working directory and not the path of the file chosen in the FileDialog.

Check out File.getAbsolutePath():
String path = new File(fd.getFile()).getAbsolutePath();

Related

Access File from Removeable Storage in Android

I am trying to access a file placed in my remove able memory card.
What I am using is
File f=new File("/mnt/sdcard/CAPP/"); // f.exists() returns True
File f=new File("/mnt/sdcard/CAPP/myfile.apk"); // f.exists() returns False
Any idea why its happening so ? Although myfile.apk is placed in CAPP folder.
Thanks in advance.
Please try this...
String getFile = Environment.getExternalStorageDirectory().toString() + "folder name" + fileName;
File file = new File(getFile );
File dir = Environment.getExternalStorageDirectory();
File yourFile = new File(dir, "path/to/the/file/inside/the/myfile.apk");

URI is not absolute?

I have a File
/user/guest/work/test/src/main/java/Test.java
And a File-Object:
File f = new File("/user/guest/work/test/src/main/java/Test.java");
I need this outputs
System.out.println(f); -> src/main/java/Test.java
System.out.println(f.getAbsolutePath()); -> /user/guest/work/test/src/main/java/Test.java
I tried:
File relativeTo = new File("/user/guest/work/test");
new File(relativeTo.toURI().relativize(f.toURI()));
but it is throwing a
java.lang.IllegalArgumentException: URI is not absolute
at java.io.File.<init>(File.java:416)
at Test.<init>(Test.java:43)
How to get the required output?
relativize returns a URI.
a new File(URI uri) takes...
uri - An absolute, hierarchical URI
You can instead try using the String constructor.
new File(relativeTo.toURI().relativize(f.toURI()).toString());
You have access to that file other ways, however
For example, you can try going through the java.nio.file.Path API instead of java.io.File
Like
Path path = Paths.get("/", "user", "guest", "workspace",
"test", "src", "main", "java", "Test.java");
Path other = ...
Path relPath = other.relativize(path);
// relPath.toString(); // print it
// relPath.toFile(); // get a file
You can use path resolve to relativize file paths
File f = new File("/user/guest/workspace/test/src/main/java/Test.java");
File relativeTo = new File("/user/guest/workspace/test");
System.out.println(new File(relativeTo.toPath().resolve(f.toPath()).toUri()));

Java saving file under same name in same directory with different extension

I'm writing a very basic java program that takes a file, does some modifications and saves the output in a different file. My problem is that I would like to save it under the same name, but with a different extension.
My current code gets the original file using the JFileChooser, converts it to a path, and uses the .resolveSibling() method. This, however, will result in test.ngc's output being saved in test.ngc.fnc
Is there any good way to save a file under the same name, but with a diffrent extension as the one selected?
Path originalFile = null;
JFileChooser chooser = new JFileChooser(".ngc");
chooser.setFileFilter(new FileNameExtensionFilter("Pycam G Code files", "ngc"));
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{
originalFile = chooser.getSelectedFile().toPath();
}
Path newFile = originalFile.resolveSibling(originalFile.getFileName() + ".fnc");
/* does reading and modification and saving here using BufferedReader and BufferedWriter*/
This should work:
String originalFilename = originalFile.getFileName();
String fileNameNew = originalFilename.substring(0, originalFilename.length()-".ngc".length())+".fnc";
Path newFile = originalFile.resolveSibling(fileNameNew);
To save the output in a different file with a different extension (.fnc), you can use regex(regular expression) to replace that using the replaceFirst method:
Path originalFile ;
String pathName ;
JFileChooser chooser = new JFileChooser(".ngc");
chooser.setFileFilter(new FileNameExtensionFilter("Pycam G Code files", "ngc"));
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
originalFile = chooser.getSelectedFile().toPath();
pathName = originalFile.toAbsolutePath().toString().replaceFirst("\\b.ngc\\b", "");
Path newFile = originalFile.resolveSibling(pathName + ".fnc");
File file = new File(newFile.toUri());
file.createNewFile();
}

JFileChooser returns wrong file name?

final JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
String fileName = fc.getSelectedFile().getName();
String path = (new File(fileName)).getAbsolutePath();
}
The absolute path I get is the concatenation of the project directory and fileName!
JFileChooser.getSelectedFile() return the File object.
Why are you getting the file name and instantiating a new File object again?
Can you try:
fc.getSelectedFile().getAbsolutePath();
That's what getAbsolutePath() does - gets the full path, including drive letter (if you're on Windows), etc. What are you trying to get, just the file name?
After you initialize your File object, you can get just the file name from that, OR you can use JFileChooser.getSelectedFile()
If you're getting /path/to/filefilename but you're expecting /path/to/file/filename then you can add an extra slash to the path as appropriate.
Sure. Because you created new file new File(fileName) using returned filename, that means relative path. Use fc.getSelectedFile().getPath() or fc.getSelectedFile().getAbsolutePath() instead.

set directory to a path in a file

I just want to set the directory to a path I have written in a file before.
Therefore I used :
fileChooser.setCurrentDirectory(new File("path.txt"));
and in path.txt the path is given. But unfortunately this does not work out and I wonder why :P.
I think I got it all wrong with the setCurrentDic..
setCurrentDirectory takes a file representing a directory as parameter. Not a text file where a path is written.
To do what you want, you have to read the file "path.txt", create a File object with the contents that you just read, and pass this file to setCurrentDirectory :
String pathWrittenInTextFile = readFileAsString(new File("path.txt"));
File theDirectory = new File(pathWrittenInTextFile);
fileChooser.setCurrentDirectory(theDirectory);
You have to read the contents of path.txt. Thea easiest way is through commons-io:
String fileContents = IOUtils.toString(new FileInputStream("path.txt"));
File dir = new File(fileContents);
You can also use FileUtils.readFileToString(..)
JFileChooser chooser = new JFileChooser();
try {
// Create a File object containing the canonical path of the
// desired directory
File f = new File(new File(".").getCanonicalPath());
// Set the current directory
chooser.setCurrentDirectory(f);
} catch (IOException e) {
}

Categories