-1

我正在尝试将数组列表的内容写入文本文件。我用我的新手编码技能部分能够做到这一点,但是目前它只将 48 行中的第一行写入文本文件。

我认为这可能是因为我的代码中没有任何循环,但是我不完全确定 id 是否需要 while 循环或 for 循环以及我需要将它放在哪里?这可能也是由于我的readFile方法使用String(readAllBytes(get(filename)))而不是逐行阅读吗?

    public static void main(String... p) throws IOException {

        List<SensorInfo> readings = new ArrayList<>();

        String filedata = readFile("client-temp.txt");

        SensorInfo info = new SensorInfo(filedata);
        readings.add(info);

        String data = createStringFromInfo(readings);
        System.out.println("Lines: " + readings.size());
        writeFile("datastore.txt", data);
    }
}

写文件

public static void writeFile(String filename, String content)
    {
        try
        {
            Files.write(get(filename), content.getBytes());
        } 
        catch (IOException e)
        {
            System.out.println("Error wiring file: " + e);
        }
    }

createStringFromInfo

public static String createStringFromInfo(List<SensorInfo> infoList)
    {
        String data = "";
        for (SensorInfo info : infoList)
        {
            data += info.asData();
        }
        return data;
    }

SensorInfo http://pastebin.com/9DDDGzwV

4

1 回答 1

0

MadProgrammer 是对的。
如果我做对了,该文件client-temp.txt有多行;每个代表来自单个SensorInfo对象的数据。当您将它们全部读入filedata并将其作为构造函数的参数传递时SensorInfo,只有第一行将用于实例化单个SensorInfo对象,正如您从发布的链接中的源代码中可以清楚地看到的那样。所有剩余的行都将被丢弃。请记住,类的构造函数将始终实例化该类的单个对象。
要解决此问题,您应该从文件中逐行读取client-temp.txt并将每个作为参数传递,以创建SensorInfo将添加到列表中的新对象。

以下是对您的新主要方法的建议:

public static void main(String[] args) {
    List<SensorInfo> readings = new ArrayList<>();

    try (BufferedReader br = new BufferedReader(new FileReader("client-temp.txt"))) {
        String line = br.readLine();

        while (line != null) {
            readings.add(new SensorInfo(line));
            line = br.readLine();
        }
    } catch (IOException e) {
        System.out.println("Unable to read data file");
        e.printStackTrace();
        System.exit(1);
    }

    String data = createStringFromInfo(readings);
    System.out.println("Lines: " + readings.size());
    writeFile("datastore.txt", data);
}

问候

于 2014-12-11T02:18:18.777 回答