在运行期间多次更新文件内容

时间:2014-03-15 16:06:46

标签: java file output

我必须在每次满足某个条件时更新文本文件的内容,这意味着我将在程序运行期间多次更新它。我正在做的是使用新文本创建一个新的临时文本文件,然后重命名它。问题是更新工作只有第一次更新通过。

这基本上就是我所拥有的:

public class FileTesting {
File file;
OutputStream fos;
InputStream fis;
String fileName;

// constructor
public FileTesting(int i) {
    try {
        if (i == 1)
            fileName = "Statistics1.txt";
        else
            fileName = "Statistics12.txt";
        file = new File((fileName));
        if (!file.isFile()) {
            file.createNewFile();
            build();
        }
        fis = new FileInputStream(file);
    } catch (IOException ex) {
    }
}

// Method for writing a line into a file
public void write(File file, String a) {
    try {
        fos = new FileOutputStream(file, true);
    } catch (FileNotFoundException e) {
    }
    PrintWriter pw = null;
    try {
        pw = new PrintWriter(new OutputStreamWriter(fos));
        pw.println(a);
    } finally {
        try {
            pw.close();
        } catch (Exception ex) {
        }
    }
}

// Increase the value on the line by one
public String increaseLine(String rida) {
    String[] parts = rida.split(": ");
    int i = Integer.parseInt(parts[1]);
    return parts[0] + ": " + (i + 1);
}

// Updates file, increasing the value on line 7 and changing the value on
// line 8 to the input
public void update(int steps) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
    File temp = new File("temp.txt");
    int i = 0;
    try {
        while (i < 7) {
            write(temp, reader.readLine());
            i++;
        }
        String lineToIncrease = reader.readLine();
        write(temp, increaseLine(lineToIncrease));
        String lineToChange = reader.readLine();
        write(temp, lineToChange.split(": ")[0] + ": " + steps);
        String line = "";
        while ((line = reader.readLine()) != null) {
            write(temp, line);
        }
        reader.close();
        file.delete();
        file = new File(fileName);
        temp.renameTo(file);

    } catch (IOException e) {
    }
}

// Initially building file
public void build() {
    int i = 0;
    while (i < 15) {

        if (i == 7)
            write(file, "Number of times read: 0");
        else if (i == 8) {
            write(file, "Some random variable steps: 100");
        } else {
            String asSting = "" + i;
            write(file, asSting);
        }
        i++;
    }

}

}

如果我使用update(...)方法两次,则只有第一个方法通过。

public static void main(String[] args) {
    FileTesting test = new FileTesting(1);
    test.update(50);
    test.update(100);

}

0 个答案:

没有答案