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.
Related
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();
}
I have convert file into DBF format. But i must save that dbf file into specific folder which has generated when i create directory. The common coding just written like this
import java.io.File;
// demonstrates how to create a directory in java
public class JavaCreateDirectoryExample
{
public static void main(String[] args)
{
File dir = new File("/Users/al/tmp/TestDirectory");
// attempt to create the directory here
boolean successful = dir.mkdir();
if (successful)
{
// creating the directory succeeded
System.out.println("directory was created successfully");
}
else
{
// creating the directory failed
System.out.println("failed trying to create the directory");
}
}
}
But, i would like change "/Users/al/tmp/TestDirectory" into a dynamic state which i take it from the path JFileChooser that i've made. Is there any possibilities to make it done? Thanks a lot
If you want to use the same variable, you can instantiate it again.
File dir = new File("/Users/al/tmp/TestDirectory");
boolean successful = dir.mkdir();
// Here we assign a new value by calling the constructor
dir = new File("/Users/al/tmp/AnotherTestDirectory");
// Next we create the new directory using the same method
boolean successful2 = dir.mkdir();
I'm guessing your quite new to Java. You should get in the habit of reading the API. It is your friend and will help answer these questions.
The JFileChooser can be used to get the selected File which can be used to get the path
JFileChooser API:
getSelectedFile() - Returns the selected file.
File API:
getAbsolutePath() - Returns the absolute pathname string of this abstract pathname.
...and some sample code
JFileChooser chooser = new JFileChooser();
int returnVal = chooser.showOpenDialog(parent);
if(returnVal == JFileChooser.APPROVE_OPTION) {
String path = chooser.getSelectedFile().getAbsolutePath();
File dir = new File(path);
....
}
I am writing a program to select file from the JFileChooser. How can I get the file type (e.g. is that file is ".txt" or ".html" of ".dat", etc.. )
I have the following code. what should i have to add extra lines?
JFileChooser choice = new JFileChooser();
int option = choice.showOpenDialog(this);
if (option == JFileChooser.APPROVE_OPTION)
{
String path=choice.getSelectedFile().getAbsolutePath();
String filename=choice.getSelectedFile().getName();
System.out.println(path);
listModel.addElement(path);
System.out.println(filename);
}
Use String#substring and String#lastIndexOf:
filename.substring(filename.lastIndexOf("."),filename.length())
If you don't want to split or substring, you can use Guava library Files (getFileExtention):
String extension = Files.getFileExtension(path);
I think this will useful.
File f = choice.getSelectedFile();
String fileType = choice.getTypeDescription(f);
I'm using the JFileChooser to allow a user to choose a .txt file that will later be processed by my program, however when the user chooses the file, it is actually opened by my computers default app (in my case TeXworks) as well as used by my program. Any idea how I can stop this?
File fileToOpen = fileChooser.getSelectedFile();
JFileChooser's getSelectedFile() method, returns a File object.
Use the getAbsolutePath() to get the absolute name to the file.
Modified example from the JavaDoc:
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
int returnVal = chooser.showOpenDialog(parent);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
System.out.println("You chose to open this directory: " + chooser.getSelectedFile().getAbsolutePath());
}
So in your case you just need to append .getAbsolutePath() to the end of your statement, like this:
File fileToOpen = fileChooser.getSelectedFile().getAbsolutePath();
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) {
}