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.
Related
I am writing a little app and would like to add the same handler for two buttons: Save and Save As. For save if the file exists it should not open the JFileChooser,just save the content, but with my current code it always opens the dialog. How do I do this? Here's my code
public void actionPerformed(ActionEvent e) {
JComponent source = (JComponent)e.getSource();
if (pathToFile.length()>0){
File file = new File(pathToFile);
if (file.exists()){
try(FileWriter fw = new FileWriter(file.getName() + ".txt", true)){
fw.write(area.getText());
}
catch(Exception ex){
System.out.println(ex.toString());
}
}
}
else{
if (fchoser.showSaveDialog(source.getParent())== JFileChooser.APPROVE_OPTION){
try(FileWriter fw = new FileWriter(fchoser.getSelectedFile()+".txt")){
fw.write(area.getText());
f.setTitle(fchoser.getSelectedFile().getPath());
pathToFile = fchoser.getSelectedFile().getPath();
}
catch(Exception ex){
}
}
}
UPDATE Added code to check if file exsists. It does and there is no exception but the additional text does not write.
Not related to your question but:
fw.write(area.getText());
Don't use the write method of a FileWriter. This will always write the text to the file using a "\n" as the line separator which may or may not be correct for the OS your code is running on.
Instead you can use the write(...) method of the JTextArea:
area.write(fw);
Then the proper line separator will be used.
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
}
}
I am trying to change a program I wrote a while ago. Currently the program handles a few BufferedReader and BufferedWriters with some logic built in. Let me explain how it used to work.
Class used to upload a file:
public void getFile(){//Used to upload the ACH file.
while(uploadApproval==false){//While upload approval has not been given..
JFileChooser chooser = new JFileChooser();//Creates a new object of the JFileChooser class.
uploadFile = chooser;//Saves the upload file variable as the chooser response.
FileNameExtensionFilter filter = new FileNameExtensionFilter("ACH Files", "ach");
//Sets the allowed file formats for upload.
chooser.setFileFilter(filter);//Activates the created file filter.
chooser.setDialogTitle("Please choose ACH file to upload");//Sets the title bar text.
//Completes once the user clicks ok.
int returnVal = chooser.showOpenDialog(chooser);//
if(returnVal == JFileChooser.APPROVE_OPTION){
uploadApproval=true;
}else{
System.exit(0);
}
}
}
Class used to set directory
public void setDirectory(){//Used to set the directory.
while(saveApproval==false){//While the user does not have approval of the save location..
JFileChooser chooser2 = new JFileChooser();//Creates a new JFileChooser object.
saveFile = chooser2;//Sets the save file location to chooser2.
chooser2.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);//User is only able to scan for
//directories.
//Completes once the user clicks okay.
int returnValue2 = chooser2.showDialog(chooser2, "Directory to save");
if(returnValue2 == JFileChooser.APPROVE_OPTION){
saveApproval=true;
}else{
System.exit(0);
}
}
}
Then later I begin the actual buffered reader/writer process which involves a lot of logic here:
location = "//NachaOutput"+randomNumber+".ACH";
try{
String sCurrentLine;//String representing the current line.
//Pulls the uploaded file.
br = new BufferedReader(new FileReader(NachaMain.uploadFile.getSelectedFile()));
bw = new BufferedWriter(new FileWriter(NachaMain.saveFile.getSelectedFile()+location));
Now here is what I need to do. I have been asked to remove the screen where the user selects the directory from the beginning. Instead, the user will select the save directory in the end of the process.
This means that the "SetDirectory" method won't be called at all, therefore this line of code:
bw = new BufferedWriter(new FileWriter(NachaMain.saveFile.getSelectedFile()+location));
obviously won't work. I need to find some way to replace that file writer location with a generic location that would be the same for all users regardless of their setup. Something along the lines of documents.
I tried doing this:
bw = new BufferedWriter(new FileWriter("Libraries\\Documents"+location));
but got an exception about an invalid path.
So please help me out and let me know a good path that I could save the file to automatically. That saved file will basically be a "dummy" file. Later in the end of the program I will copy that dummy file to the location the user specifies then delete it, so the location really doesn't matter too much.
Thanks in advance!
You could create a temporary file using File.createTempFile(). It might make cleanup easier if you called deleteOnExit() for the created temporary file.
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());
I need to save a text File which is already created in a particular path given by JFileChooser. What I do basically to save is:
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
int status = chooser.showSaveDialog(null);
if (status == JFileChooser.APPROVE_OPTION) {
System.out.print(chooser.getCurrentDirectory());
// Don't know how to do it
}
How to save the text file in a path given by JFileChooser?
You want to add the following after if statement:
File file = chooser.getSelectedFile();
FileWriter fw = new FileWriter(file);
fw.write(foo);
where foo is your content.
EDIT:
As you want to write a text file, I'd recommend the following:
PrintWriter out = new PrintWriter(file);
BufferedReader in = new BufferedReader(new FileReader(original));
while (true)
{
String line = in.nextLine();
if (line == null)
break;
out.println(line);
}
out.close();
where original is the file containing data you want to write.
create a new File object with the path and name for the file
File file = new File(String pathname)
Try this:
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
int status = chooser.showSaveDialog(null);
if (status == JFileChooser.APPROVE_OPTION) {
FileWriter out=new FileWriter(chooser.getSelectedFile());
try {
out.write("insert text file contents here");
}
finally {
out.close();
}
}
// ...
You'll need the filename you want to save under in addition to the directory provided by chooser.getCurrentDirectory(), but that should do what you need it to. Of course, you'll need to write the save method that actually writes to the stream, too, but that's up to you. :)
EDIT: There's a much method to use, chooser.getSelectedFile(), that should be used here, per another answer in the thread. Updated to use that method.
EDIT: Since OP specified the file being written is a text file, I've added code to write the contents of the file. Of course, you'll need to replace "insert text file contents here" with the actual file contents to write.