How to save the text file in a path given by JFileChooser? - java

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.

Related

Java saving file under same name in same directory with different extension

I'm writing a very basic java program that takes a file, does some modifications and saves the output in a different file. My problem is that I would like to save it under the same name, but with a different extension.
My current code gets the original file using the JFileChooser, converts it to a path, and uses the .resolveSibling() method. This, however, will result in test.ngc's output being saved in test.ngc.fnc
Is there any good way to save a file under the same name, but with a diffrent extension as the one selected?
Path originalFile = null;
JFileChooser chooser = new JFileChooser(".ngc");
chooser.setFileFilter(new FileNameExtensionFilter("Pycam G Code files", "ngc"));
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{
originalFile = chooser.getSelectedFile().toPath();
}
Path newFile = originalFile.resolveSibling(originalFile.getFileName() + ".fnc");
/* does reading and modification and saving here using BufferedReader and BufferedWriter*/
This should work:
String originalFilename = originalFile.getFileName();
String fileNameNew = originalFilename.substring(0, originalFilename.length()-".ngc".length())+".fnc";
Path newFile = originalFile.resolveSibling(fileNameNew);
To save the output in a different file with a different extension (.fnc), you can use regex(regular expression) to replace that using the replaceFirst method:
Path originalFile ;
String pathName ;
JFileChooser chooser = new JFileChooser(".ngc");
chooser.setFileFilter(new FileNameExtensionFilter("Pycam G Code files", "ngc"));
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
originalFile = chooser.getSelectedFile().toPath();
pathName = originalFile.toAbsolutePath().toString().replaceFirst("\\b.ngc\\b", "");
Path newFile = originalFile.resolveSibling(pathName + ".fnc");
File file = new File(newFile.toUri());
file.createNewFile();
}

Set default saving extension with JFileChooser

I'm trying to save a file using JFileChooser. However, I seem to be having some trouble with it. Here's my code:
if (e.getSource() == saveMenu) {
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
FileNameExtensionFilter xmlFilter = new FileNameExtensionFilter("xml files (*.xml)", "xml");
// add filters
chooser.addChoosableFileFilter(xmlFilter);
chooser.setFileFilter(xmlFilter);
int result = chooser.showSaveDialog(Simulation.this);
if (result == chooser.APPROVE_OPTION) {
writeToXML(chooser.getSelectedFile());
}
}
This doesn't force the file to have a .xml extension, so I've tried to use the following code to force the file to be saved with the extension .xml
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
XMLWriter xmlWriter = null;
try {
xmlWriter = new XMLWriter(new OutputStreamWriter(
new FileOutputStream(f+".xml"), "UTF8"),
format);
However, with this I can't prevent the user from writing xpto.xml in the JFileChooser and if they do that, the file will have "two extensions": it will be a file named xpto.xml.xml
So my questions are:
How can I make the JFileChooser save an xml file by default?
If the user inserts a file name like xpto.xml, how can I save it as xpto.xml and not xpto.xml.xml?
As you've noticed, JFileChooser doesn't enforce the FileFilter on a save. It will grey-out the existing non-XML file in the dialog it displays, but that's it. To enforce the filename, you have to do all the work. (This isn't just a matter of JFileChooser sucking -- it's a complex problem to deal with. Your might want your users to be able to name their files xml.xml.xml.xml.)
In your case, I recommend using FilenameUtils from Commons IO:
File file = chooser.getSelectedFile();
if (FilenameUtils.getExtension(file.getName()).equalsIgnoreCase("xml")) {
// filename is OK as-is
} else {
file = new File(file.toString() + ".xml"); // append .xml if "foo.jpg.xml" is OK
file = new File(file.getParentFile(), FilenameUtils.getBaseName(file.getName())+".xml"); // ALTERNATIVELY: remove the extension (if any) and replace it with ".xml"
}
There's also some ideas for what to do if you want multiple types in the save dialog here: How to save file using JFileChooser?
Just to make things clear as to how to use the JFileChooser to save files.
//set it to be a save dialog
chooser.setDialogType(JFileChooser.SAVE_DIALOG);
//set a default filename (this is where you default extension first comes in)
chooser.setSelectedFile(new File("myfile.xml"));
//Set an extension filter, so the user sees other XML files
chooser.setFileFilter(new FileNameExtensionFilter("xml file","xml"));
now the user was encouraged to save the item as an xml file in this example, but they may not have actually set it.
if(chooser.showSaveDialog(this) == jFileChooser.APPROVE_OPTION) {
String filename = chooser.getSelectedFile().toString();
if (!filename .endsWith(".xml"))
filename += ".xml";
//DO something with filename
}
This is the most simple case, if you have multiple possible file formats, then you should catch the selected filter, verify THAT extension, and also save the file according to the selected format. but if you are doing that, you are probably an advanced java programmer and not utilizing this post.
How about something like this:
else if (e.getSource() == saveMenu) {
int returnVal = chooser.showSaveDialog(Simulator.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
String fname = file.getAbsolutePath();
if(!fname.endsWith(".xml") ) {
file = new File(fname + ".xml");
if(!file.createNewFile()) {
/*check with user??*/
}
You should try this:
if(!file.getName().contains(".")) file = new File(file.toString() + ".xml");
You should try this. I did this and it worked.
FileOutputStream fileOut = new FileOutputStream(file1+".xml");
hwb.write(fileOut);
fileOut.close();
System.out.println("\n Your file has been generated!");
JOptionPane.showMessageDialog(this,"File Created.");

Reading a txt file in a Java GUI

All I want to do is display the entire contents of a txt file. How would I go about doing this? I'm assuming that I will set the text of a JLabel to be a string that contains the entire file, but how do I get the entire file into a string? Also, does the txt file go in the src folder in Eclipse?
This code to display the selected file contents in you Jtext area
static void readin(String fn, JTextComponent pane)
{
try
{
FileReader fr = new FileReader(fn);
pane.read(fr, null);
fr.close();
}
catch (IOException e)
{
System.err.println(e);
}
}
To choose the file
String cwd = System.getProperty("user.dir");
final JFileChooser jfc = new JFileChooser(cwd);
JButton filebutton = new JButton("Choose");
filebutton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (jfc.showOpenDialog(frame) !=JFileChooser.APPROVE_OPTION)
return;
File f = jfc.getSelectedFile();
readin(f.toString(), textpane);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
frame.setCursor(Cursor.
getPredefinedCursor(
Cursor.DEFAULT_CURSOR));
}
});
}
});
All I want to do is display the entire contents of a txt file. How
would I go about doing this? I'm assuming that I will set the text of
a JLabel to be a string that contains the entire file but how do I get the entire file into a string?
You would be better of using a JTextArea to do this. You can also look at the read() method.
does the txt file go in the src folder in Eclipse?
Nope. You can read files from any where. The tutorial on "Reading, Writing, and Creating Files" would be a good place to start
create text file in your project's working folder
read your text file line by line
store the line contents in stringBuilder variable
then append next line contents to stringBuilder variable
then assign the content of your StringBuilder variable to the JLabel's text property
But it is not good idea to store whole file's data into JLabel, use JTextArea or any other text containers.
Read your file like this:
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
}
String everything = sb.toString();
} finally {
br.close();
}
now assign value of everything to JLabel or JTextArea
JLabel1.text=everything;
Use java.io to open a file stream.
Read content from file by lines or bytes.
Append content to StringBuilder or StringBuffer
Set StringBuilder or StringBuffer to JLable.text.
But I recommend using JTextArea..
You don't need to put this file in src folder.

Saving to a specific directory

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.

save file with JFileChooser save dialog

I have written a Java program that opens all kind of files with a JFileChooser. Then I want to save it in another directory with the JFileChooser save dialog, but it only saves an empty file. What can I do for saving part?
Thanks.
JFileChooser just returns the File object, you'll have to open a FileWriter and actually write the contents to it.
E.g.
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
FileWriter fw = new FileWriter(file);
fw.write(contents);
// etc...
}
Edit:
Assuming that you simply have a source file and destination file and want to copy the contents between the two, I'd recommend using something like FileUtils from Apache's Commons IO to do the heavy lifting.
E.g.
FileUtils.copy(source, dest);
Done!
Just in addition to Kris' answer - I guess, you didn't read the contents of the file yet. Basically you have to do the following to copy a file with java and using JFileChooser:
Select the source file with the FileChooser. This returns a File object, more or less a wrapper class for the file's filename
Use a FileReader with the File to get the contents. Store it in a String or a byte array or something else
Select the target file with the FileChooser. This again returns a File object
Use a FileWriter with the target File to store the String or byte array from above to that file.
The File Open Dialog does not read the contents of the file into memory - it just returns an object, that represents the file.
Something like..
File file = fc.getSelectedFile();
String textToSave = mainTextPane.getText();
BufferedWriter writer = null;
try
{
writer = new BufferedWriter( new FileWriter(file));
writer.write(textToSave);
JOptionPane.showMessageDialog(this, "Message saved. (" + file.getName()+")",
"ImPhil HTML Editer - Page Saved",
JOptionPane.INFORMATION_MESSAGE);
}
catch (IOException e)
{ }

Categories