JFileChooser that manually picks the file - java

I was just wondering. Is there any way to use JFileChooser but open the file manually? So I could put the directory somewhere in code before and then just load it?
Here is part of my code:
JFileChooser fc = new JFileChooser();
if (fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
try {
File plik = fc.getSelectedFile();
Scanner skaner = new Scanner(plik);
while (skaner.hasNext())
dialog.append(skaner.nextLine() + "\n");
}
catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}
So I want to:
Open file from directory so i won't have to choose the "something.txt".
Piece of code that let me open another file in the same JTextArea one by one, by clicking the JButton.
What I really need is a piece of code that lets me load txt file (from directory) by clicking a button few times in a row.
Is this even possible?

You can use setSelectedFile method of the JFileChooser to 'pre-select' the File, the user will only have to click OK if the file exists.

JTextArea directory=new JTextArea();
directory.setText(System.getProperty("user.home"));
directory.setEditable(true);
JFileChooser choose=new JFileChooser(directory.getText());

Related

How to get file path from JavaFX FileChooser?

I have a simple JavaFX window with a TextField for users to enter a file path and a separate browse link.
JavaFX Window
I'd like to ask how to extract the full file path of the selected file from JavaFX FileChooser (so I can set the path in the TextField)?
I understand what I'm trying to achieve can be done simply with Swing JFileChooser with something like:
JFileChooser chooser = new JFileChooser();
String someString = chooser.getSelectedFile().toString();
But since my application is in JavaFX I want it to have a consistent look and not a mix with Swing.
I've looked through the documentation, there doesn't seem to be a method for this https://docs.oracle.com/javase/8/javafx/api/javafx/stage/FileChooser.html
Thanks in advance.
Here's another documentation. What you get in return from using showOpenDialog is a File object.
public File showOpenDialog(Window ownerWindow)
Shows a new file open dialog. The method doesn't return until the
displayed open dialog is dismissed. The return value specifies the
file chosen by the user or null if no selection has been made. If the
owner window for the file dialog is set, input to all windows in the
dialog's owner chain is blocked while the file dialog is being shown.
A file object has various methods like e. g. getAbsolutePath.
Use showOpenDialog or showSaveDialog (depending on whether you want to open an existing file or save a new one). Both return a File object.
In the controller class where you have the TextField you can create a method like so:
public void getTheUserFilePath() {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Upload File Path");
fileChooser.getExtensionFilters().addAll(
new FileChooser.ExtensionFilter("ALL FILES", "*.*"),
new FileChooser.ExtensionFilter("ZIP", "*.zip"),
new FileChooser.ExtensionFilter("PDF", "*.pdf"),
new FileChooser.ExtensionFilter("TEXT", "*.txt"),
new FileChooser.ExtensionFilter("IMAGE FILES", "*.jpg", "*.png", "*.gif")
);
File file = fileChooser.showOpenDialog(dialogPane.getScene().getWindow());
if (file != null) {
// pickUpPathField it's your TextField fx:id
pickUpPathField.setText(file.getPath());
} else {
System.out.println("error"); // or something else
}
}

Can you create a file on the system clipboard but not in a directory?

When a user clicks a button I would like to generate and add the file to the system clipboard. I have been able to do this, but when the file is added to the system clipboard, it also generates the file in the project folder (I'm using Eclipse). Can I make it directly on the system clipboard and not have it show up in a directory?
When I make a file, here is the code I use:
File file = new File("file.txt");
should "file.txt" be replaced with a path to the system clipboard? Or is that not possible?
StringSelection sel = new StringSelection(<insert string here>);
Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
clip.setContents(sel, sel);
You can view this for string selection http://docs.oracle.com/javase/8/docs/api/java/awt/datatransfer/StringSelection.html
Do not create a file in the path of your project. You know that when you create file using the following statement:
File file = new File("file.txt");
It is being created near the class file of your code.
Just create a temp file using the createTempFile static method of class File :
try {
File f = File.createTempFile("file", ".txt");
FileWriter wr = new FileWriter(f);
wr.write("This is a Test!");
wr.close();
// Add it to clipboard here
} catch (IOException e) {
e.printStackTrace();
}
Good Luck

How to get complete file name and path of file which is opened in java program?

i created an html editor and i want to get the file name & path of opened file in the JTextPane. any suggestion?
Assuming you make use of the File chooser (the file picker), which seems quite likely for a code editor you could simply save the file path you receive as a result:
public void actionPerformed(ActionEvent e) {
//Handle open button action.
if (e.getSource() == openButton) {
int returnVal = fc.showOpenDialog(FileChooserDemo.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
//At this point you can use: file.getName() to get your filename
//You can also use file.getPath()
} else {
//Canceled opening
}
}
}
You could save the result of file.getName() and file.getPath() to a string that you would assign to your JTextPane later on.
For additional information on file choosers see the documentation which also explains this process in more detail.
Should you be working with File you can make use of the same functions which will provide the same information.

java - JFileChooser - open/cancel/exit button

I made a button that will create a JFileChooser so the user can open a .txt file, here's the code inside the action listener of the button:
JFileChooser fc = new JFileChooser();
//filter-show only .txt files
FileNameExtensionFilter txtfilter = new FileNameExtensionFilter("txt files (*.txt)", "txt");
//apply the filter to file chooser
fc.setFileFilter(txtfilter);
fc.setDialogTitle("Otvori txt file");
//disable the ability to show files of all extensions
fc.setAcceptAllFileFilterUsed(false);
//create file chooser via jFrame
fc.showOpenDialog(jFrame);
//get selected file
File selFile = fc.getSelectedFile();
Path path = Paths.get(selFile.toString());
asdf = selFile.toString();
//display chosen file on jLabel5
jLabel5.setText(path.getFileName().toString());
It works just fine, if you select the .txt file inside the file chooser, but it also works if you just select a file and then press cancel and exit. I assume it's because of the getSelectedFile() but I am wondering if there is a way to make sure the user selected a file and pressed open inside file chooser as a condition to get a file?
You should check whether the return value from:
fc.showOpenDialog(jFrame) == JFileChooser.APPROVE_OPTION
That return value indicates how the user exited the dialog.
See JFileChooser.showOpenDialog(Component) docs.

Saving already Opened File in JFileChooser Java?

How to save a file if it is already opened without opening the FileChooser dialog like notepad ?
It took me so much time to figure out. I've searched the net but could not find something could help me here.
Thanks in Advance
My issue is in the code below. The new edit is not saved. I opened the same file and nothing was saved (not updated I mean)
fileWriter = new BufferedWriter(new
FileWriter(openFile.getSelectedFile().getPath()));
private class FileAction implements ActionListener{
public void actionPerformed(ActionEvent e){
//JOptionDialog
JFileChooser openFile = new JFileChooser();
openFile.setFileFilter(new txtFilter());
if(e.getSource() == open ){
int openOption = openFile.showOpenDialog(frame);
textArea.setText(""); //clearing the Text_AREA before opening the new file
try{
Scanner scan = new Scanner(new FileReader(openFile.getSelectedFile().getPath()));
while(scan.hasNext())
textArea.append(scan.nextLine() + "\n");
}catch(Exception ex){
//ShowDialogBox dialogBox = new ShowDialogBox();
JOptionPane.showMessageDialog(frame,"Please choose .txt File only");
}
}
} else if( e.getSource() == save){ //SAVE_BUTTON
try{
BufferedWriter fileWriter = new BufferedWriter(new FileWriter(openFile.getSelectedFile().getPath())); //(This does not save at all I opened the file again and still as it was before editing)
fileWriter.write(textArea.getText());
fileWriter.close();
}catch(Exception ex){
}
}
}
}
Without knowing more, I assume you get a NullPointerException since when save (it is a button, right?) is pressed, the action creates a new JFileChooser instance which hasn't a selected file yet.
So you should store the selected file when it is opened in an instance variable (use openFile.getSelectedFile() in the open branch) and pass that file handle to the FileWriter that is created in the save branch.
If you're reusing the same instance of FileAction you could put the reference there, otherwise you could put it somewhere else (maybe some container object that is passed to the action) where multiple instances of FileAction have access to.
Just a word in advance: do resist the temptation to use a static variable, that's not an appropriate usage of statics.
Not related to your problem but you should NOT be using fileWriter.write(...).
Instead you should be using textArea.write(...). See Text and New Lines for more information.

Categories