将Java中的长字符串写入文件

发布于 2024-12-11 07:18:50 字数 748 浏览 0 评论 0原文

我正在尝试将一个大整数数组(10 000 个元素)转储到文本文件中,但遇到了一些问题。我尝试了两种不同的方法,但似乎都不起作用。下面是我编写的函数:

private static void writeToFile(String name, int[] a){
    try {
        FileWriter fw = new FileWriter(name);
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write("working");
        for (int n: a){
            bw.write(n + " ");
        }
        bw.close();
    } catch (IOException e) {
        System.err.print("Unable to write to file " + name+ ".");
        e.printStackTrace();
    }
}

我尝试的第一件事是在 for 循环中创建一个字符串,然后将整个字符串写入文件。这两种方法都不起作用,并给出了相同的结果,如下所示:

  1. 文件已创建但留空
  2. 对于较短的数组(〜10个元素)
  3. 工作正常如果空格是字母,例如:bw.write(n +“a”)

任何想法我做错了什么?或者还有我没有看到的更简单的方法吗?

谢谢,
西瓦特里克斯

I'm trying to dump a large integer array (10 000 elements) into a text file but am encountering some problems. I've tried two different approaches and neither seems to be working. Below is the function I've written:

private static void writeToFile(String name, int[] a){
    try {
        FileWriter fw = new FileWriter(name);
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write("working");
        for (int n: a){
            bw.write(n + " ");
        }
        bw.close();
    } catch (IOException e) {
        System.err.print("Unable to write to file " + name+ ".");
        e.printStackTrace();
    }
}

The first thing I tried was creating a string in the for loop and then writing the whole string to the file. Neither method works and gives me the same results as follows:

  1. File is created but left blank
  2. Works fine for shorter arrays (~10 elements)
  3. Works fine if the space is a letter eg: bw.write(n + "a")

Any idea what I'm doing wrong? Or is there an even easier way that I'm not seeing?

Thanks,
Civatrix

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

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

发布评论

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

评论(2

凉月流沐 2024-12-18 07:18:50

您能解释一下您之后如何查看/阅读文件吗?据我所知,您的代码基本上很好(禁止将 close() 移动到finally块),并且无论添加空格还是其他字母,它实际上应该没有任何区别。但这可能会对文本编辑器产生影响,我想......?

Can you explain how you're viewing/reading in the file afterwards? Your code is basically fine as far as I can see (bar moving the close() to a finally block), and it really should make no difference whatsoever whether a space or other letter is added. But that might make a difference e.g. to a text editor, I suppose...?

空城仅有旧梦在 2024-12-18 07:18:50

该代码会将 a[] 的所有元素写入文件,后跟一个空格,除非出现异常。但是它不会写任何行。这是你的问题吗?如果是这样,则在每个 write() 之后需要 bw.newLine()

That code will write all the elements of a[] to the file followed by a space, unless it gets an exception. However it won't write any lines. Is that your problem? If so, you need bw.newLine() after each write().

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