【问题标题】:Write data in file using java that data was returned by function使用 java 将数据写入文件中,该数据由函数返回
【发布时间】:2016-10-17 19:39:00
【问题描述】:

我想在另一个函数返回数据的文件中写入数据。

我可以在控制台中看到所有值,但在文件中看不到。任何想法?谢谢

for (int dx = 1; dx <= 100; dx++) {

    try {

        File file = new File("file.txt");
        file.createNewFile();

        FileWriter write = new FileWriter(file);

        String sizeX = (String.valueOf(Myclass.myFunction(a, b));

        write.write(sizeX);
        write.flush();
        write.close();

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

private static Random random = new Random();

public static int myFunction(int a, int b) {
    return (int) (random.myFunction(a*b);
}

【问题讨论】:

  • 首先,您正在创建一个文件并将其写入循环中。所要做的就是不断地将同一行写入文件而不是附加它,这就是我认为您正在尝试做的事情。将文件打开和关闭操作移到 for 循环之外。
  • 这个问题比较模糊,Matt 是正确的,你不断地用你的 for 循环的每次迭代覆盖你的文件

标签: java


【解决方案1】:

for 循环之外但在try/catch 块内创建、刷新和关闭文件。

    try {

        File file = new File("file.txt");
        file.createNewFile();

        FileWriter writer = new FileWriter(file);

        for (int dx = 1; dx <= 100; dx++) {
            String sizeX = (String.valueOf(Myclass.myFunction(a, b));
            writer.write(sizeX);
        }

        writer.flush();
        writer.close();

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

private static Random random = new Random();

public static int myFunction(int a, int b){
    return (int) (random.myFunction(a*b);
}

您可能希望在数字之间放置一个分隔符以使输出更清晰,即:

writer.write(sizeX + "|");

【讨论】:

  • 谢谢。是的,这就是我要找的。​​span>
【解决方案2】:

我认为这更像是你想要完成的事情

编辑 - 看起来有人已经打败了我!

要在下面添加他的答案,他是正确的,您不应该像我在下面写的那样在循环内调用刷新。以下是一个很好的解释:

Here in this SO post

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;

public class test
{

    private static Random randomFunction = new Random();

    public static void main(String[] args) throws IOException
    {

        FileWriter write = null;

        try
        {
            File file = new File("file.txt");
            file.createNewFile();
            write = new FileWriter(file);

            for (int dx = 1; dx <= 100; dx++)
            {
                String sizeX = String.valueOf(myFunction(34, 43));
                write.append(sizeX);
                write.flush();
            }

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

        try
        {
            write.close();
        }
        catch (Exception x)
        {
            x.printStackTrace();
        }
    }

    public static int myFunction(int a, int b)
    {
        return randomFunction.nextInt((a * b));
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    • 1970-01-01
    • 2019-12-04
    相关资源
    最近更新 更多