FileChooser getAttachement only from this Folder - java

How to make the user to select the file from only specified folder
int returnVal = fc.showOpenDialog(FileChooser.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
source = file.getAbsolutePath();
fileName = file.getName();
attachText.setText(fileName);
source = source.replace("\\","\\\\");
}
Here I will get the file from any folder, where I want the file only from G:\Project\Attachments. How Can i do this?

File dir = new File("G:\\Project\\Attachments");
FileSystemView fsv = new SingleRootFileSystemView(dir);
JFileChooser fileChooser = new JFileChooser(fsv);
int returnVal = fc.showOpenDialog(fileChooser);
if (returnVal == JFileChooser.APPROVE_OPTION) {

You can pass the directory in the constructor:
JFileChooser filechooser = new JFileChooser(theDirectory);
or set it
filechooser.setCurrentDirectory(theDirectory);
in your case the directory is:
File theDirectory = new File("G:\\Project\\Attachments");

Related

Adding a Search field to a Jfilechooser

I have created JFileChooser and I need to add search functionality when a user browse for a particular folder to locate a certain file with ease such the JFilechooser should have a text field where user can type and filter other files in a given directory. How can I achieve this in java?
Here is My sample code that implements basic file browsing.
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("Excell File Only", "csv");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
if (chooser.getSelectedFile() != null) {
path.setText(chooser.getSelectedFile().getName());
}}

JFileChooser getCurrentDirectory() to String

I have this code:
JFileChooser openFolder = new JFileChooser();
openFolder.setCurrentDirectory(new java.io.File("."));
openFolder.setDialogTitle("Select target directory");
openFolder.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
openFolder.setAcceptAllFileFilterUsed(false);
if (openFolder.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{
File newLoc = openFolder.getCurrentDirectory();
}
How can I make it so that It converts this:
File newLoc = openFolder.getCurrentDirectory();
To a String if its possible?
For example using the FileChooser I chose the folder: C:\Music
I tried using:
String locToString = FileUtils.readFileToString(newLoc);
but it doesn't work.
I want to convert it to string so I can make it appear on a JTextField using:
jTextField.setText(locToString);
newLoc.getAbsolutePath() will give you a String from a File, per the javadoc.

opening a javafx FileChooser in the user directory

I am trying to open a javafx FileChooser in the user directory according to an example I found here.
Here is a fragment of the simple code I am using:
FileChooser fc = new FileChooser();
fc.setTitle("Open Dialog");
String currentDir = System.getProperty("user.dir") + File.separator;
file = new File(currentDir);
fc.setInitialDirectory(file);
However, I keep obtaining this warning (complete file paths have been truncated):
Invalid URL passed to an open/save panel: '/Users/my_user'. Using 'file://localhost/Users/my_user/<etc>/' instead.
I verified that the file object is an existing directory adding these lines:
System.out.println(file.exists()); //true
System.out.println(file.isDirectory()); //true
Then I do not have idea why I am obtaining the warning message.
UPDATE:
This seems to be a bug in JavaFX: https://bugs.openjdk.java.net/browse/JDK-8098160
(you need to create a free Jira account to see the bug report).
This problem happens in OSX, no idea about other platforms.
This is what I ended up doing and it worked like a charm.
Also, make sure your folder is accessible when trying to read it (good practice). You could create the file and then check if you can read it. Full code would then look like this, defaulting to c: drive if you can't access user directory.
FileChooser fileChooser = new FileChooser();
//Extention filter
FileChooser.ExtensionFilter extentionFilter = new FileChooser.ExtensionFilter("CSV files (*.csv)", "*.csv");
fileChooser.getExtensionFilters().add(extentionFilter);
//Set to user directory or go to default if cannot access
String userDirectoryString = System.getProperty("user.home");
File userDirectory = new File(userDirectoryString);
if(!userDirectory.canRead()) {
userDirectory = new File("c:/");
}
fileChooser.setInitialDirectory(userDirectory);
//Choose the file
File chosenFile = fileChooser.showOpenDialog(null);
//Make sure a file was selected, if not return default
String path;
if(chosenFile != null) {
path = chosenFile.getPath();
} else {
//default return value
path = null;
}
This works on Windows and Linux, but might be different on other operating systems (not tested)
Try:
String currentDir = System.getProperty("user.home");
file = new File(currentDir);
fc.setInitialDirectory(file);
#FXML private Label label1; //total file path print
#FXML private Label labelFirst; //file dir path print
private String firstPath; //dir path save
public void method() {
FileChooser fileChooser = new FileChooser();
if (firstPath != null) {
File path = new File(firstPath);
fileChooser.initialDirectoryProperty().set(path);
}
fileChooser.getExtensionFilters().addAll(
new ExtensionFilter("Text Files", "*.txt"),
new ExtensionFilter("Image Files", "*.png", "*.jpg", "*.gif"),
new ExtensionFilter("Audio Files", "*.wav", "*.mp3", "*.aac"),
new ExtensionFilter("All Files", "*.*") );
File selectFile = fileChooser.showOpenDialog(OwnStage);
if (selectFile != null){
String path = selectFile.getPath();
int len = path.lastIndexOf("/"); //no detec return -1
if (len == -1) {
len = path.lastIndexOf("\\");
}
firstPath = path.substring(0, len);
labelFirst.setText("file path : " + firstPath);
label1.setText("First File Select: " + path);
}
}

File renameTo does not work

I am trying to add an extension to the name of file selected by a JFileChooser although I can't get it to work.
This is the code :
final JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal = fc.showSaveDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File f = fc.getSelectedFile();
String name =f.getAbsoluteFile()+".txt";
f.renameTo(new File(name));
FileWriter fstream;
try {
fstream = new FileWriter(f);
BufferedWriter out = new BufferedWriter(fstream);
out.write("test one");
out.close();
} catch (IOException ex) {
Logger.getLogger(AppCore.class.getName()).log(Level.SEVERE, null, ex);
}
}
I can't figure out why this doesn't work. I also tried using getPath() and getCanonicalPath() but the result is the same. The file is created at the directory selected, although without a ".txt" extension.
It seems to me that all you want to do is to change the name of the file chosen, as opposed to renaming a file on the filesystem. In that case, you don't use File.renameTo. You just change the File. Something like the following should work:
File f = fc.getSelectedFile();
String name = f.getAbsoluteFile()+".txt";
f = new File(name);
File.renameTo attempts to rename a file on the filesystem. For example:
File oldFile = new File("test1.txt");
File newFile = new File("test2.txt");
boolean success = oldFile.renameTo(newFile); // renames test1.txt to test2.txt
After these three lines, success will be true if the file test1.txt could be renamed to test2.txt, and false if the rename was unsuccessful (e.g. test1.txt doesn't exist, is open in another process, permission was denied, etc.)
I will hazard a guess that the renaming you are attempting is failing because you are attempting to rename a directory (you are using a JFileChooser with the DIRECTORIES_ONLY option). If you have programs using files within this directory, or a Command Prompt open inside it, they will object to this directory being renamed.
You could also use the Files.move utility from Google Guava libraries to rename a file. Its easier than writing your own method.
From the docs:
Moves the file from one path to another. This method can rename a file or move it to a different directory, like the Unix mv command.
You are writing to the wrong file. When you call renameTo, the current file doesn't change it's path. Try this:
final JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal = fc.showSaveDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File f = fc.getSelectedFile();
String name =f.getAbsoluteFile()+".txt";
File f2 = new File(name);
f.renameTo(f2);
FileWriter fstream;
try {
fstream = new FileWriter(f2);
BufferedWriter out = new BufferedWriter(fstream);
out.write("test one");
out.close();
} catch (IOException ex) {
Logger.getLogger(AppCore.class.getName()).log(Level.SEVERE, null, ex);
}
}
If you want to Rename the file then there is must to close all the object (like FileReader,FileWriter ,FIS ,FOSmeans close the the reading file object and then rename it
You need to create a new instance to refer to the new name of the file
oldFile = new File(newName);

Modification to JFileChooser to just display folder content

i m trying to develop an gui application which display tree of filesystem on left side and on right side it display selected tree nodes (folder)'s content .
can any body tell me to do modification in jfilechooser to just to display folder content
thank you in advance
The JFileChooser#accept allows you to filter which files are displayed. A similar method is the JFileChooser#setFileFilter method
See: example
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
Perhaps this is what you expected:-
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
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 e1) {
e1.printStackTrace();
}
// Show the dialog; wait until dialog is closed
int returnVal = chooser.showOpenDialog(frame);
if(returnVal == JFileChooser.APPROVE_OPTION)
{
File f = chooser.getSelectedFile();
textField.setText(f.getAbsolutePath());
File[] contents = f.listFiles();
for(int file=0;file<contents.length;file++)
{
System.out.println(contents[file].getName()); //here you get the contents of the selected directory
}
}

Categories

Resources