0

I'm trying to get my submit button to save the GUI in a text file, I've made the GUI and the button listener ...etc but I'm having trouble making the method that saves the information from the GUI into a text file.

so far i have:

public void save() {

    File k1 = new File("documents/"+"newfile.txt");
    try {
       k1.createNewFile();
       FileWriter kwriter = new FileWriter(k1);

       BufferedWriter bwriter = new BufferedWriter(kwriter);
       bwriter.write(txtField1.getText().trim());
       bwriter.newLine();
       bwriter.close();

    } catch (IOException e) {
       e.printStackTrace();
    }
}

but it doesn't seem to work, nothing happens; is there anything I'm missing?

4
  • Try using an absolute file path. Commented Nov 30, 2010 at 23:02
  • 2
    FYI - instead of documents/ .. use "documents"+File.separator+"newfile.txt"; Commented Nov 30, 2010 at 23:02
  • @CoolBeans: Good Call. Definitely important for portability (!) Commented Nov 30, 2010 at 23:09
  • @sova No it isn't. Java is smart enough to automatically use the native separator if you use / Commented Nov 30, 2010 at 23:19

5 Answers 5

2

You're file is called .txt - perhaps insert a name in the first row:

File k1 = new File("documents/filename.txt");
Sign up to request clarification or add additional context in comments.

7 Comments

Or mayby use flush() before close the file?? like bwriter.flush()
Could you try writing out a text like this: bwriter.write("just something"); - and removing the row k1.createNewFile();, since making a FileWriter will implicitly create the file.
You could also try to give an absolute path to the file. Since the working directory of your java process may be somewhere you're not expecting it to be.
.close() does an implicit flush.
sorry none of those work, except the absolute path (which i havent tried) how can i implement that?
|
1

You should be getting an error when running that code. The problem is that the document directory doesn't exist or it is not where you expected.

You can check for the parent directory with:

if(!k1.getParentFile().exists()){
    k1.getParentFile().mkdirs();
}

Alternatively you need to set the file to be a more precise location. org.apache.commons.lang.SystemUtils might be able to help you out here with user home.

Comments

0

i was just think is there a easier way, for example i already have the Jfilechoser open a "save as box" when the "submit" button is pressed so is there a easier way to create the file (saving the gui infomation in a txt file) ?

This is a continuation on your previous question. You should just get the selected file and write to it with help of any Writer, like PrintWriter.

File file = fileChooser.getSelectedFile();
PrintWriter writer = new PrintWriter(file);
try {
    writer.println(txtField1.getText().trim());
    writer.flush();
} finally {
    writer.close();
}

Don't overcomplicate by creating a new File() on a different location and calling File#createFile(). Just writing to it is sufficient.

See also:


update here's an SSCCE, you can just copy'n'paste'n'compile'n'run it.

package com.example;

import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

import javax.swing.JFileChooser;

public class Test {

    public static void main(String[] args) throws IOException {
        JFileChooser fileChooser = new JFileChooser();
        if (fileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
            File file = fileChooser.getSelectedFile();
            PrintWriter writer = new PrintWriter(file);
            try {
                writer.println("Hello");
                writer.flush();
            } finally {
                writer.close();
            }
            Desktop.getDesktop().open(file);
        }
    }

}

9 Comments

im getting a few errors with the above code, 1) it doesnt like "writer"??? also it doesnt like "printWriter" and "fileChooser"???
says "can not find symbol for each of those
You need to add the necessary import statements like import java.io.PrintWriter; and so on. The fileChooser is obviously the JFileChooser as given in your previous question. Are you using an IDE like Eclipse (which can add import statements automagically) or a text editor like notepad? Once you become familiar with Java basics, I can recommend an IDE.
cheers mate, im using notepad++ but have just downloaded eclipe. thanks again
I've added a copy'n'paste'n'compilable'n'runnable SSCCE to the answer.
|
0

My guess is that the file is being created, but not in the directory that you expect. Check the value of the user.dir system property and see what it shows. This is the current working directory of your JVM.

You may need to either:

  • Specify a full path in the code (as Martin suggested), e.g. new File("/home/foo/newfile.txt")
  • Change the working directory of the JVM. The way that you do this depends on how you are launching it (e.g. if you are running the java command directly from a CLI, then just switch directories first, if you are running from an IDE then change the launch configuration, etc.).

As far as I know, you cannot change the working directory at runtime (see this SO question).

1 Comment

or add a System.out.println(k1.getAbsolutePath()); to quickly check where the file is written
0

Your code is working for me with minor change.

As a debugging process, I would completely delete the directory path and try to use a file only..

instead of

File k1 = new File("documents/"+"newfile.txt");

use

File k1 = new File("newfile.txt");

Check where your file is generated and then create directory there..

Good luck!!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.