Iam a java beginner.
I have written a simple program to write some contents to a file using showSaveDialoge() in JFileChooser. The code including below.
public static void main(String arg[]) throws IOException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException
{
JFrame frame = new JFrame();
JFileChooser fc = new JFileChooser();
try {
File file = new File("fileName.txt");
fc.setSelectedFile(file);
int r = fc.showSaveDialog(frame);
if(r == JFileChooser.APPROVE_OPTION)
{
FileWriter writer = new FileWriter(file);
writer.append("Data inside the file");
writer.flush();
writer.close();
}
else if(r == JFileChooser.CANCEL_OPTION) {
System.out.println("Do nothing for CANCEL");
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "File could not be written, try again.");
}
}
the code gets executed and Save Dialogue box has come. But when I click SAVE button on Dialogue box, nothing had happening. The file has not saved in the selected location. What may be the reason.?
Thanks in advance.
What is hapenning is:
you create a File in your current location with name fileName.txt
File file = new File("fileName.txt"); //could be $HOME$/fileName.txt
User selects ProgramFiles/file.txt
but you uses on FileWritter file information, not what user chossed from FileChooser.
change
FileWriter writer = new FileWriter(file);
to
FileWriter writer = new FileWriter(chooser.getSelectedFile());
Try this:
FileWriter writer = new FileWriter(fc.getSelectedFile());
It should write to selected file from file chooser.
You were writing to fileName.txt which will be saved in current directory from which you run program.
Related
I'm playing around and I made a notepad-like app using swing. Everything is working properly so far, except it's not letting me save the text file directly on C:/. On any other disk, and INCLUDING the root of the D: drive, or in folders of the C:/ disk it works like a charm. Why is this happening?
This is my code:
file_save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JFileChooser Chooser = new JFileChooser();
File DefaultDirectory = new File("C:/");
File Path;
int Checker;
FileFilter text_filter = new FileNameExtensionFilter(
"Text File (*txt)", "txt");
FileFilter another_filter = new FileNameExtensionFilter(
"Debug Filter (*boyan)", "boyan");
//
Chooser.setCurrentDirectory(DefaultDirectory);
Chooser.setDialogTitle("Save a file");
Chooser.addChoosableFileFilter(text_filter);
Chooser.addChoosableFileFilter(another_filter);
Chooser.setFileFilter(text_filter);
Checker = Chooser.showSaveDialog(null);
//
if (Checker == JFileChooser.APPROVE_OPTION) {
Path = Chooser.getSelectedFile();
System.out.println(Path.getAbsolutePath());
;// Just for
// debugging.
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(Path
.getAbsolutePath()));
String[] myString = textArea.getText().split("\\n");
for (int i = 0; i < textArea.getLineCount(); i++) {
writer.append(myString[i]);
writer.newLine(); // SO IT CAN PRESERVE NEW LINES
// (APPEND AND SPLIT ARE ALSO
// THERE
// BECAUSE OF THAT)
writer.flush();
}
JOptionPane.showMessageDialog(null, "File saved.", "",
JOptionPane.WARNING_MESSAGE);
} catch (IOException e) {
JOptionPane.showMessageDialog(null,
"File did not save successfuly.", "",
JOptionPane.WARNING_MESSAGE);
} finally {
try {
if (writer != null)
writer.close();
} catch (IOException e) {
JOptionPane.showMessageDialog(null,
"File did not save successfuly.", "",
JOptionPane.WARNING_MESSAGE);
}
}
}
}
});
Thanks a lot in advance!
Usually, one does not have write permissions in C:\.
Start the app as a privileged user
One should not do that, as it is not intended by OS design. Changing permissions on C:\, or the system drive respectively, is a no-go.
Save into a sub-directory of System.getProperty("user.home"); (way to go)
The user home could also be a network folder with nighly backup in a domain network, for example. Especially for remote sessions (RDP, Citrix), this is often the case.
If you absolutely need to install a static file outside of the users folders, do it once, with an installer, configured to raise privileges (UAC).
while i am trying to save the file its not working but for making folders it works. what should i do ? i am new in java also. plz help
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==save)
{
JFrame parentFrame = new JFrame();
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Specify a file to save");
int userSelection = fileChooser.showSaveDialog(parentFrame);
if (userSelection == JFileChooser.APPROVE_OPTION)
{
File fileToSave = fileChooser.getSelectedFile();
System.out.println("Save as file: " + fileToSave.getAbsolutePath());
}
}
}
You choose a file but don't create it write anything to it. The file will not be created until you actually create it or write something to it, for example with
FileWriter writer = new FileWriter(fileToSave);
writer.write("Hello!");
writer.close();
First, get the file you want to save as a File.
Then, write it to a new directory using BufferedWriter to a new directory.
final JFileChooser fc = new JFileChooser();
int returnVal = fc.showSaveDialog(aComponent); //parent component to JFileChooser
if (returnVal == JFileChooser.APPROVE_OPTION) { //OK button pressed by user
File file = fc.getSelectedFile(); //get File selected by user
o = new BufferedWriter(new FileWriter(file)); //use its name
//write things here
o.flush();
o.close();
}
Look at How to save file using JFileChooser in Java? and How to save a txt file using JFileChooser?
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.
I have chosen file using
File file = fileChooser.getSelectedFile();
Now I want to write this file chosen by user to another location when user clicks save button. How to achieve that using swing?
To select the file you need something like ,
JFileChooser open = new JFileChooser();
open.showOpenDialog(this);
selected = open.getSelectedFile().getAbsolutePath(); //selected is a String
...and to save a copy ,
JFileChooser save = new JFileChooser();
save.showSaveDialog(this);
save.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
tosave = fileChooser.getSelectedFile().getAbsolutePath(); //tosave is a String
new CopyFile(selected,tosave);
...the copyFile class will be something like,
public class CopyFile {
public CopyFile(String srFile, String dtFile) {
try {
File f1 = new File(srFile);
File f2 = new File(dtFile);
InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f2);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
System.out.println("File copied.");
} catch (FileNotFoundException ex) {
System.out.println(ex.getMessage() + " in the specified directory.");
System.exit(0);
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
Also have a look at this question : How to save file using JFileChooser? #MightBeHelpfull
Swing will just give you the location/File object. You are going to have to write the new file yourself.
To copy the file, I will point you to this question: Standard concise way to copy a file in Java?
If you are using JDK 1.7 you can use the java.nio.file.Files class which offers several copy methods to copy a file to a given destiny.
read the file into a InputStream and then write it out to an OutputStream.
I'm currently trying to save a newly created text file to a directory that the user specifies. However, I don't see how it is possible with this code setup. Where does one specify where file is to be saved?
if(arg.equals(Editor.fileLabels[1])){
if(Editor.VERBOSE)
System.err.println(Editor.fileLabels[1] +
" has been selected");
filedialog = new FileDialog(editor, "Save File Dialog", FileDialog.SAVE);
filedialog.setVisible(true);
if(Editor.VERBOSE){
System.err.println("Exited filedialog.setVisible(true);");
System.err.println("Save file = " + filedialog.getFile());
System.err.println("Save directory = " + filedialog.getDirectory());
}
File file = new File("" + filedialog.getName());
SimpleFileWriter writer = SimpleFileWriter.openFileForWriting(filedialog.getFile() + ".txt");
if (writer == null){
System.out.println("Failed.");
}
writer.print("" + this.editor.getTextArea().getText());
writer.close();
}
FileChooser and FileWriter make things fairly easy, here is the java tutorial:
http://download.oracle.com/javase/tutorial/uiswing/components/filechooser.html
http://www.abbeyworkshop.com/howto/java/writeText/index.html
You call it like this:
JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(aComponent);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
File toSave = fc.getSelectedFile();
FileWriter outWriter = new FileWriter(toSave);
PrintWriter outPrinter = new PrintWriter(outWriter);
outPrinter.println("" + this.editor.getTextArea().getText());
}
else
{
//user pressed cancel
}
Remember that it is the PrintWriter class that does the actual printing.
EDIT:
If you want the user to select directories only, call
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
before displaying it. Note that in this case you will have to specify a new File object WITHIN that directory in order to be able to write text to it (attempting to write the text to a directory will result in an IOException).
writer.print("" + this.editor.getTextArea().getText());
Don't use methods like that. All text components support a write(...) method. All you have to do is get the File name that you want to write the file to.
Something like:
JtextArea textArea = new JTextArea(....);
....
FileWriter writer = new FileWriter( "TextAreaLoad.txt" ); // get the file name from the JFileChooser.
BufferedWriter bw = new BufferedWriter( writer );
textArea.write( bw );
bw.close();
If you don't know how to use file choosers then read the section from the Swing tutorial on How to Use File Choosers.