Saving to a specific directory - java

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.

Related

Export text file and added names in the text field

My code is when user type in the Name text filed, it will export as text file and record the Name.
For example,
I typed 1st time "James" in the Name text filed, it will appear
"James" in the text file. I type second time "Agnes" , it appears
"Agnes" in the text file. But It only appear one name in the text
file.
I want all the names appear whatever user type in the text filed.
How do i modify my codes?
try
{
new JTextField();
// create new file
String path="C:\\export.txt";
File file = new File(path);
// if file doesnt exists, then create it
if (!file.exists())
{
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
// write in file
// bw.write(txtName.getText());
if (txtName.getText() ==null)
{
bw.write(txtName.getText());
bw.write('\n');
System.out.print("1st Name:" +txtName.getText());
}
else
if (txtName.getText()!=null)
{
// bw.write('\n');
bw.write(txtName.getText());
System.out.print("2nd Name:" +txtName.getText());
}
// close connection
bw.flush();
bw.close();
fw.close();
}
catch(Exception e)
{
System.out.println(e);
}
Please advise.Thanks
You should use append mode when write file, like:
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
Edit again:
FileWriter fileWritter = new FileWriter(file.getName(),true);
BufferedWriter bw = new BufferedWriter(fileWritter);
if (txtName.getText()!=null){
//this line edited
bw.write(txtName.getText()+"\n");
System.out.print("2nd Name:" +txtName.getText());
}

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.");

How to save the text file in a path given by 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.

Overwriting a text file when i don't want it to. - Java

I am working on a log file that is currently over-writing itself every single time. Now The thing is all i want it to do is to just write on the first line and append the list below to show the history from newest to oldest. Problem is I am not sure how to go about it I am looking at the code but don't know what I am doing wrong. Here is the code not sure if I am missing something or not.
String historylog = new Date().toString();
BufferedWriter bw = null;
String filepath = "C:\netbeans\Source code\test3";
String filename = "PatchHistory.log";
try
{
if (!(new File( filepath).exists()))
(new File( filepath)).mkdirs();
bw = new BufferedWriter( new FileWriter( filepath + File.separator
+ filename, true));
bw.write( historylog + "\r\n");
bw.newLine();
bw.flush();
bw.close();
return true;
}
catch (IOException){
return false;
}
Any Help would be appreciated not sure what I am doing wrong with this.
If I have understood you, you want to add log entries at the beginning of a log file.
AFAIK, (if you know any exceptions please tell me) all filesystems add data to the end of file. And Direct Access would overwrite the beginning of the file.
Your best option would be writting the log to a different file and, after writting what you want, write after that the contents of the original log file. Once done, close both files and overwrite the old file with the new one.
In your code
You are wrong here, you didn't used if statement properly.
if (!(new File( filepath).exists()))
(new File( filepath)).mkdirs(); // file path not exist, then it will execute
bw = new BufferedWriter( new FileWriter( filepath + File.separator + filename, true)); // this append file will always execute
Solution
if (!(f.exists())) {
//create new file
bw = new BufferedWriter(new FileWriter(filepath + File.separator + filename, false));
}
else{
//append in existing file
bw = new BufferedWriter(new FileWriter(filepath + File.separator + filename,true));
}

Filehandling file path

Basically i have two questions. i am using the below code to read and write z text file.
File myFile = new File("/sdcard/mysdfile.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append("my text here");
myOutWriter.close();
this create a new file every time i want this to OPEN_OR_CREATE(if file already exist don't create a new one)
Ad my second question is that how to change the path "/sdcard/mysdfile.txt" i want this file to stored in my sdcard -> subFolder1 -> SubFolder2
Thnaks
Do not use hardcoded /sdcard or /mnt/sdcard or your app will fail as devices vary on location or mountpoint of that storage. To get the right location use
Environment.getExternalStorageDirectory();
See docs here.
To append content to existing file use new FileOutputStream(myFile, true); instead of just new FileOutputStream(myFile); - see docs on that constructor here.
As for
how to change the path "/sdcard/mysdfile.txt"
Aside from getting rid of /sdcard as said above, just add subfolders to the paths: MyFolder1/MyFolder2/mysdfile.txt. Note these folder have to exists or the path will be invalid. You can always create it by calling myFile.mkdirs().
Replace
FileOutputStream fOut = new FileOutputStream(myFile);
with
FileOutputStream fOut = new FileOutputStream(myFile, true); //true means append mode.
Appart from that I have one suggestion for you.
Never never hardcode /sdcard in code,Rather consider writing.
File myFile = new File(Environment.getExternalStorageDirectory(),"mysdfile.txt");
Try my solution to write to end of text file
private void writeFile (String str){
try {
File f = new File(Environment.getExternalStorageDirectory().toString(),"tasklist.txt");
FileWriter fw = new FileWriter(f, true);
fw.write(str+"\n");
fw.flush();
fw.close();
} catch (Exception e) {
}
}
*File(Environment.getExternalStorageDirectory().toString()+"your/pth/here","tasklist.txt");
File dir = Environment.getExternalStorageDirectory();
File f = new File(dir+"/subFolder1/",xyz.txt); <-- HOW TO USE SUB FOLDER
if(file.exists())
{
// code to APPEND
}
else
{
// code to write new one
}
1> OPEN_OR_CREATE
You can try or can replace MODE_APPEND with true like #Vipul's suggestion
FileOutputStream fOut = openFileOutput(your_path_file, MODE_APPEND);
//it means if the file is exist the content you want write will append into it.
2> stored in my sdcard -> subFolder1 -> SubFolder2
you can use Environment.getExternalStorageDirectory().getAbsolutePath() to get full file path the SDCard. Then concat strings to get the file path you want. Ex:
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "myFile.txt";
File f = new File(baseDir + File.separator + subfolder1 + File.separator + subfoler2, fileName);
In Java 7 we can do it this way:
Path path = Paths.get("/sdcard/mysdfile.txt");
BufferedWriter wrt = Files.newBufferedWriter(path, StandardCharsets.UTF_8, StandardOpenOption.APPEND);

Categories