-1

我正在使用以下模式创建和写入文件:

File afile = new File("C:/dev/ws/DataOrdering/data/" + thisDate
                + "_" + thisTime + "_visdata.csv");
FileWriter writer = new FileWriter(afile);
writer.append(tradeDetails);
writer.close();

但是由于某种原因,只有第一个文件被写入,之后文件是空的 - 只有在特定时间有记录时才会创建它们,因为文件名基于从记录中获取的时间. 我的完整方法打印在下面。(我已经对其进行了编辑以反映我所做的更改)。

public void createTimeFiles() throws IOException {

    CSVReader reader = new CSVReader(new FileReader(
            "C:/dev/ws/DataOrdering/data/visdata.csv"));

    String[] nextLine;
    String lastTime = "";
    String code, date, hour, min, sec, offset, type, price, volume, bid, ask, headline;

    HashMap<Integer, FileWriter> writers = new HashMap<Integer, FileWriter>();
    while ((nextLine = reader.readNext()) != null) {
        String thisDate = nextLine[1];
        String thisTime = nextLine[2].substring(0, 5);

        code = nextLine[0];
        date = nextLine[1];
        hour = nextLine[2].substring(0, 2);
        min = nextLine[2].substring(3, 5);
        sec = nextLine[2].substring(6);
        offset = nextLine[3];
        type = nextLine[4];
        price = nextLine[5];
        volume = nextLine[6];
        bid = nextLine[7];
        ask = nextLine[7];
        headline = nextLine[7];

        // System.out.println(thisDate + " - " + thisTime + " - " + hour
        // + " - " + min);
        String tradeDetails = code + " _ " + date + " _ " + hour + " _ "
                + min + " _ " + sec + " _ " + offset + " _ " + type + " _ "
                + price + " _ " + volume + " _ " + bid + " _ " + ask
                + " _ " + headline;

        File afile = new File("C:/dev/ws/DataOrdering/data/" + thisDate
                + "_" + thisTime + "_visdata.csv");
        if (afile.exists()) {
            FileWriter writer = new FileWriter(afile);
            writer.append(tradeDetails);
            writer.close();
        } else {
            System.out.println("the file exists");
            FileWriter writer = new FileWriter(afile);
            writer.write(tradeDetails);
            writer.close();
        }

    }
}
4

4 回答 4

2

文件是否存在?你是在附加,而不是在写......

于 2009-09-21T15:59:34.313 回答
1

检查你的“ !

            if (!afile.exists()) { // here
                    System.out.println("the file exists");
                    FileWriter writer = new FileWriter(afile);
                    writer.append(tradeDetails);
                    writer.close();
            } else {
                    FileWriter writer = new FileWriter(afile);
                    writer.append(tradeDetails);
                    writer.close();
            }

为什么你做两次同样的事情?如果文件不存在。你必须写,而不是追加。

该文件夹也可能不存在。

aFile.getParentFile().mkdirs();

如果父文件夹已经存在,则没有问题。

于 2009-09-21T16:00:51.127 回答
0

也许 visdata.csv 不存在或不包含任何数据,因此不会写入任何内容。

C:/dev/ws/DataOrdering/data/visdata.csv存在吗?

于 2009-09-21T15:59:26.153 回答
0

称呼

writer.flush();

打电话之前

writer.close();
于 2009-09-21T16:08:09.840 回答