使用Java无法保存到文本文件

发布于 2024-10-05 20:25:31 字数 560 浏览 8 评论 0原文

我正在尝试让我的提交按钮将GUI保存在文本文件中,我已经制作了GUI和按钮侦听器...等,但我在制作保存方法时遇到了麻烦将 GUI 中的信息写入文本文件。

到目前为止我已经:

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();
    }
}

但它似乎不起作用,什么也没有发生;我有什么遗漏的吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

心如狂蝶 2024-10-12 20:25:31

您的文件名为 .txt - 也许在第一行插入一个名称:

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

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

File k1 = new File("documents/filename.txt");
北笙凉宸 2024-10-12 20:25:31

运行该代码时您应该会收到错误。
问题是文档目录不存在或者不在您期望的位置。

您可以通过以下方式检查父目录:

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

或者,您需要将文件设置为更精确的位置。
org.apache.commons.lang.SystemUtils 也许可以帮助您处理用户主页。

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.

柏林苍穹下 2024-10-12 20:25:31

我只是想有没有更简单的方法,例如,当按下“提交”按钮时,我已经让 Jfilechoser 打开“另存为框”,所以有没有更简单的方法来创建文件(保存 gui 信息)在 txt 文件中)?

这是您的上一个问题的延续。您应该获取选定的文件并在任何 Writer,如 PrintWriter

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

不要通过在不同位置创建 new File() 并调用 File#createFile() 来使事情变得过于复杂。只需写入它就足够了。

另请参阅:


更新 这里SSCCE,您只需复制、粘贴、编译、运行即可。

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);
        }
    }

}

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);
        }
    }

}
不必了 2024-10-12 20:25:31

我的猜测是该文件正在创建,但不在您期望的目录中。检查 user.dir 系统属性的值并查看它显示的内容。这是 JVM 的当前工作目录。

您可能需要:

  • 在代码中指定完整路径(如 Martin 建议),例如 new File("/home/foo/newfile.txt")
  • 更改 JVM 的工作目录。执行此操作的方式取决于您启动它的方式(例如,如果您直接从 CLI 运行 java 命令,则只需先切换目录,如果您从 IDE 运行,则更改启动配置等)。

据我所知,您无法在运行时更改工作目录(请参阅 this SO问题)。

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

泪眸﹌ 2024-10-12 20:25:31

您的代码只需稍作更改即可为我工作。

作为调试过程,我将完全删除目录路径并尝试仅使用文件..

而不是

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

使用

< code>File k1 = new File("newfile.txt");

检查文件的生成位置,然后在那里创建目录..

祝你好运!

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!!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文