I want to limit my users to a directory and its sub directories but the "Parent Directory" button allows them to browse to an arbitrary directory.
How should I go about doing that?
Incase anyone else needs this in the future:
class DirectoryRestrictedFileSystemView extends FileSystemView
{
private final File[] rootDirectories;
DirectoryRestrictedFileSystemView(File rootDirectory)
{
this.rootDirectories = new File[] {rootDirectory};
}
DirectoryRestrictedFileSystemView(File[] rootDirectories)
{
this.rootDirectories = rootDirectories;
}
#Override
public File createNewFolder(File containingDir) throws IOException
{
throw new UnsupportedOperationException("Unable to create directory");
}
#Override
public File[] getRoots()
{
return rootDirectories;
}
#Override
public boolean isRoot(File file)
{
for (File root : rootDirectories) {
if (root.equals(file)) {
return true;
}
}
return false;
}
}
You'll obviously need to make a better "createNewFolder" method, but this does restrict the user to one of more directories.
And use it like this:
FileSystemView fsv = new DirectoryRestrictedFileSystemView(new File("X:\\"));
JFileChooser fileChooser = new JFileChooser(fsv);
or like this:
FileSystemView fsv = new DirectoryRestrictedFileSystemView( new File[] {
new File("X:\\"),
new File("Y:\\")
});
JFileChooser fileChooser = new JFileChooser(fsv);
You can probably do this by setting your own FileSystemView.
The solution of Allain is almost complete. Three problems are open to solve:
Clicking the "Home"-Button kicks the user out of restrictions
DirectoryRestrictedFileSystemView is not accessible outside the package
Starting point is not Root
Append #Override to DirectoryRestrictedFileSystemView
public TFile getHomeDirectory()
{
return rootDirectories[0];
}
set class and constructor public
Change JFileChooser fileChooser = new JFileChooser(fsv); into JFileChooser fileChooser = new JFileChooser(fsv.getHomeDirectory(),fsv);
I use it for restricting users to stay in a zip-file via TrueZips TFileChooser and with slight modifications to the above code, this works perfectly. Thanks a lot.
No need to be that complicated. You can easily set selection mode of a JFileChooser like this
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.setMultiSelectionEnabled(false);
You can read more reference here How to Use File Choosers
Related
I have a button in a toolbar which has to save what I am drawing in a JFrame in Java. It works but it currently acts as a 'Save As' button. I am trying to make it overwrite the file once it is saved without showing a dialog. Can someone help me fix it?
My code:
JFileChooser fileChooser2;
this.fileChooser2 = new JFileChooser();
fileChooser2.addChoosableFileFilter(new TxtFilter2());
EDIT
public class TxtFilter2 extends FileFilter
{
public boolean accept(java.io.File file)
{
if (file.isDirectory())
return true;
return (file.getName().endsWith("xml"));
}
public String getDescription()
{
return "Save (*.xml)";
}
}
This is the button itself with the action:
if (ev.getActionCommand()=="Save2")
{
fileChooser2.setDialogType(JFileChooser.SAVE_DIALOG);
fileChooser2.setDialogTitle("Save as XML file format");
res=this.fileChooser2.showSaveDialog(this);
if (res==JFileChooser.APPROVE_OPTION)
{
this.net.saveToFile(fileChooser2.getSelectedFile().getPath()+".xml");
}
}
You could store the file or at least the path to the file in a member variable once the user saves for the first time. This would allow you to recognize whether the drawing has already been saved and allow you to overwrite it.
First you need a field to store the file/path:
private File savedFile;
then you can use it to overwrite it:
if (ev.getActionCommand().equals("Save2")) {
//Check if the drawing has already been saved, if not open the dialog
if(this.savedFile == null) {
fileChooser2.setDialogType(JFileChooser.SAVE_DIALOG);
fileChooser2.setDialogTitle("Save as XML savedFile format");
int res = this.fileChooser2.showSaveDialog(this);
if (res == JFileChooser.APPROVE_OPTION) {
final File selectedFile = fileChooser2.getSelectedFile();
//Store the selected file in the member variable
this.savedFile = selectedFile;
this.net.saveToFile(selectedFile.getPath() + ".xml");
}
}else {
//Use the previously selected file and don't show the dialog
this.net.saveToFile(this.savedFile.getPath() + ".xml");
}
}
I'm not sure if that's what you want to do and I don't know what exactly your this.net.saveToFile() method does but I hope this helps
I have a JFileChooser and i want to have different options available in the type which will change the extension. The options i want are
.txt
.html
.xml
Right now I have:
JFileChooser chooser = new WritableFileChooser(Model.getSingleton().getOptionsParam().getUserDirectory());
chooser.setFileFilter(new FileFilter()
{
#Override
public boolean accept(File file)
{
if (file.isDirectory())
{
return true;
}
else if (file.isFile())
{
String lcFileName = file.getName().toLowerCase(Locale.ROOT);
return (lcFileName.endsWith(TXT_FILE_EXTENSION) || lcFileName.endsWith(HTML_FILE_EXTENSION) || lcFileName.endsWith(XML_FILE_EXTENSION) }
return false;
}
#Override
public String getDescription()
{
return Constant.messages.getString("file.format.html");
}
But only All files and HTML are available in the file type filter. Ideally, i also want to get rid of the All files options.
Also i have two different format .html's that are to be generated, is there any indicator i can add so that the file chooser is smart enough to know which one i want?
As #AndrewMcCoist said, the Oracle Tutorial on Filters is somewhat helpful but i got my answer and solution from this example.
chooser .addChoosableFileFilter(new FileNameExtensionFilter("PDF Documents", "pdf"));
chooser .addChoosableFileFilter(new FileNameExtensionFilter("MS Office Documents", "docx", "xlsx", "pptx"));
chooser .addChoosableFileFilter(new FileNameExtensionFilter("Images", "jpg", "png", "gif", "bmp"));
I need to read all ".txt" files from folder (user needs to select this folder).
Please advise how to do it?
you can use filenamefilter class it is pretty simple usage
public static void main(String[] args) throws IOException {
File f = new File("c:\\mydirectory");
FilenameFilter textFilter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".txt");
}
};
File[] files = f.listFiles(textFilter);
for (File file : files) {
if (file.isDirectory()) {
System.out.print("directory:");
} else {
System.out.print(" file:");
}
System.out.println(file.getCanonicalPath());
}
}
just create an filenamefilter instance an override accept method how you want
Assuming you already have the directory, you can do something like this:
File directory= new File("user submits directory");
for (File file : directory.listFiles())
{
if (FileNameUtils.getExtension(file.getName()).equals("txt"))
{
//dom something here.
}
}
The FileNameUtils.getExtension() can be found here.
Edit: What you seem to want to do is to access the file structure from the web browser. According to this previous SO post, what you want to do is not possible due to security reasons.
You need to read the directory and iterate inside it.
it is more a question on Java access to file systems than about MVC
I wrote the following function that will search for all the text files inside a directory.
public static void parseDir(File dirPath)
{
File files[] = null;
if(dirPath.isDirectory())
{
files = dirPath.listFiles();
for(File dirFiles:files)
{
if(dirFiles.isDirectory())
{
parseDir(dirFiles);
}
else
{
if(dirFiles.getName().endsWith(".txt"))
{
//do your processing here....
}
}
}
}
else
{
if(dirPath.getName().endsWith(".txt"))
{
//do your processing here....
}
}
}
see if this helps.
provide a text box to user to enter the path of directory.
File userDir=new File("userEnteredDir");
File[] allfiles=useDir.listFiles();
Iterate allFiles to filter .txt files using getExtension() method
I have an FXML controller class with a textfield that I want populated with various file properties of a file a user selects via a FileChooser.
The controller looks like:
#FXML
TextField documentName;
File file;
public void attachNewDocFileChooser() {
file = new MyFileChooser().chooser();
if (file != null) {
documentName.setText(file.getName());
} else {
documentName.setText("No file selected");
}
}
The FileChooser is created in a different class MyFileChooser:
#FXML
public File chooser() {
File file = null;
final JFileChooser fileDialog = new JFileChooser();
int returnVal = fileDialog.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
file = fileDialog.getSelectedFile();
}
return file;
}
I can't get the textfield documentName populated with the name of the file selected.
I'll be very grateful for any help at making this work. Thank you all in advance.
Update:
I get a java.lang.NullPointerException.
I also forgot to mention that chooser() is linked to a Label so that onMouseClicked="#chooser".
The only NullPointerException could be for documentName still being null. That is, that the #FXML did not work. Check the line number of the exception to see whether that is the case. And then go looking into the .fxml file you loaded.
#FXML(name="documentName")
public TextField documentName;
I need to read all ".txt" files from folder (user needs to select this folder).
Please advise how to do it?
you can use filenamefilter class it is pretty simple usage
public static void main(String[] args) throws IOException {
File f = new File("c:\\mydirectory");
FilenameFilter textFilter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".txt");
}
};
File[] files = f.listFiles(textFilter);
for (File file : files) {
if (file.isDirectory()) {
System.out.print("directory:");
} else {
System.out.print(" file:");
}
System.out.println(file.getCanonicalPath());
}
}
just create an filenamefilter instance an override accept method how you want
Assuming you already have the directory, you can do something like this:
File directory= new File("user submits directory");
for (File file : directory.listFiles())
{
if (FileNameUtils.getExtension(file.getName()).equals("txt"))
{
//dom something here.
}
}
The FileNameUtils.getExtension() can be found here.
Edit: What you seem to want to do is to access the file structure from the web browser. According to this previous SO post, what you want to do is not possible due to security reasons.
You need to read the directory and iterate inside it.
it is more a question on Java access to file systems than about MVC
I wrote the following function that will search for all the text files inside a directory.
public static void parseDir(File dirPath)
{
File files[] = null;
if(dirPath.isDirectory())
{
files = dirPath.listFiles();
for(File dirFiles:files)
{
if(dirFiles.isDirectory())
{
parseDir(dirFiles);
}
else
{
if(dirFiles.getName().endsWith(".txt"))
{
//do your processing here....
}
}
}
}
else
{
if(dirPath.getName().endsWith(".txt"))
{
//do your processing here....
}
}
}
see if this helps.
provide a text box to user to enter the path of directory.
File userDir=new File("userEnteredDir");
File[] allfiles=useDir.listFiles();
Iterate allFiles to filter .txt files using getExtension() method