除非append为true,否则FileWriter方法不会打印任何内容

时间:2018-09-05 13:51:41

标签: java file append

新手在这里。我的目标是读取一个txt文件,消除字符(“-”和“”),并用新的清理文本替换现有文本。

示例:855-555-1234 >> 8555551234。

我陷入了我的附加布尔值。我正在使用指南herehere

当我的append为true时,我会在文件末尾得到想要的文本,但是如果为false,则文件完全为空白。

我的主要方法如下:

public class Main {

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

    String file_name = "C:/TollFreeToPort.txt";
    try {
        ReadFile file = new ReadFile(file_name);
        String[] aryLines = file.OpenFile();

        WriteFile data = new WriteFile(file_name, true);

        int i;

        for (i = 0; i < aryLines.length; i++) {

            System.out.println(aryLines[i]);
            data.writeToFile(aryLines[i]);
        }
    } catch (IOException e) {
        System.out.println(e.getMessage());
    }
  }
}

我的ReadFile类:

package textfiles;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;

public class ReadFile {

private String path;

public ReadFile(String file_path) {
    path = file_path;
}

public String[] OpenFile() throws IOException {
    FileReader fr = new FileReader(path);
    BufferedReader textReader = new BufferedReader(fr);

    int numberOfLines = readLines();
    String[] textData = new String[numberOfLines];

    int i;

    for (i = 0; i < numberOfLines; i++) {
        textData[i] = textReader.readLine()
        .replace("-", "")
        .replace(" ", "");
    }

    textReader.close();

    return textData;

}

int readLines() throws IOException {
    FileReader file_to_read = new FileReader(path);
    BufferedReader bf = new BufferedReader(file_to_read);

    String aLine;
    int numberOfLines = 0;

    while ((aLine = bf.readLine()) != null) {
        numberOfLines++;
    }
    bf.close();

    return numberOfLines;
  }
}

我的WriteFile类:

package textfiles;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.IOException;

public class WriteFile {

private  String path;
private boolean append_to_file = false;

public WriteFile(String file_path) {
    path = file_path;
}

public WriteFile(String file_path, boolean append_value) {
    path = file_path;
    append_to_file = append_value;
}

public void writeToFile (String textLine) throws IOException{
    FileWriter write = new FileWriter(path, append_to_file);
    PrintWriter print_line = new PrintWriter(write);

    print_line.printf("%s" + "%n", textLine);
    print_line.close();
  }
}

0 个答案:

没有答案