java检查文本文件是否存在而不覆盖

时间:2015-11-19 12:41:15

标签: java printwriter

我想检查一个文本文件是否存在,并设置一个PrintWriter来写入。现在,任何新的PrintWriter实例都会覆盖最后一个实例。 我的主要:

TextFileForStatus textFile = new TextFileForStatus();
int startingIndex = 1; 

try{
    String output = textFile.readIndex();
    System.out.println("In file: " + output);
    if(output == null)
    {
        textFile.writeToFile(Integer.toString(startingIndex));
    }
    else {
        System.out.println("output: " + output);
        startingIndex = Integer.parseInt(output);
    }
} catch(ReaderException RE){
    RE.getMessage().toString();
}catch(Exception EX){
    EX.getMessage().toString();
}

以及我创建的用于创建文件的类:

public class TextFileForStatus {

    private final String fileName = "status";
    private final String Format =  "UTF-8";
    private BufferedReader reader = null;
    private PrintWriter writer = null;

    public TextFileForStatus() throws FileNotFoundException, UnsupportedEncodingException {
        writer = new PrintWriter(fileName, Format);
        reader = new BufferedReader(new FileReader(fileName));
    }
    public void writeToFile(String currentStatus){
        writer.println(currentStatus);
        System.out.println("writer wrote: "+ currentStatus + " to file");
        writer.flush();
    }
    public String readIndex() throws IOException{
        String indexInFile = "";
        while((indexInFile = reader.readLine())!=null){
            indexInFile += reader.readLine();
        }
        return indexInFile;
    }
}

我可以使用已存在的文本文件吗?

2 个答案:

答案 0 :(得分:2)

您可以使用class MasterActor extends UntypedActor { Router router; { List<Routee> routees = new ArrayList<Routee>(); for (int i = 0; i < 5; i++) { ActorRef r = getContext().actorOf(Props.create(Worker.class, getSelf())); getContext().watch(r); routees.add(new ActorRefRoutee(r)); } router = new Router(new RoundRobinRoutingLogic(), routees); } public void onReceive(Object message) throws Exception { if(message instanceof Work) { router.route(message, sender()); } if(message instanceof CompletedJob) { //handle a job completed update } } } 检查文件是否存在。所以你可能想尝试:

new File(fileName).exists()

答案 1 :(得分:1)

使用JDK7文件:

public void writeToFile(String path, String fileName, String status) throws Exception {
    String text = "writer wrote: "+ status + " to file";
    Path p = Paths.get(path, fileName);
    if (Files.isWritable(p)) { //checks for existence too
        Files.write(p, text.getBytes(), StandardOpenOption.APPEND); // see https://docs.oracle.com/javase/tutorial/essential/io/file.html#openOptions
    }
}

检查OpenOption是否有写作选项。