Java IO创建/附加文件 [英] Java IO Create / Append File

查看:159
本文介绍了Java IO创建/附加文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个文件,如果它不存在,如果它存在追加到它。
这是最好的方法吗?我不知道有一个方法里面有两个尝试是好的,亲自?

  public static void main(String [] args)
{
String fileLocation =/ temp / ;
String name =Bob;
String timeStamp =1988-03-15;
Path path = Paths.get(fileLocation +info.log); (!Files.exists(path)){
try {
Files.createFile(path);

if
} catch(IOException e){
e.printStackTrace();



(BufferedWriter writer = Files.newBufferedWriter(StandardCharsets.UTF_8,StandardOpenOption.APPEND)){
SimpleDateFormat tTimeFormatter = new SimpleDateFormat( yyyy / MM / dd HH:mm:ss:SSS);
writer.write(tTimeFormatter.format(System.currentTimeMillis())+name:+ name +Timestamp:+ timeStamp);
writer.newLine();
} catch(IOException e){
System.out.print(e.getStackTrace());



$ div $解析方案

可以使用StandardOpenOptions写入文件:CREATE和APPEND。
$ b $ pre $ Files.write(Paths.get(),new byte [ ] {},StandardOpenOption.CREATE,StandardOpenOption.APPEND);

CREATE - 表示如果文件不存在则创建新文件,否则存在。
APPEND - 表示将新数据添加到文件中的现有内容中。

因此,您可以使用一行代码执行所有操作。


Im trying to create a file if it doesnt exist, if it does exist append to it. Is this the best way to do it? Im not sure having two try catches inside one method is good personally?

   public static void main(String [] args)
    {
        String fileLocation = "/temp/";
        String name = "Bob";
        String timeStamp = "1988-03-15";
        Path path = Paths.get(fileLocation+ "info.log");

        if(!Files.exists(path)){
            try {
                Files.createFile(path);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        try (BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) {
            SimpleDateFormat tTimeFormatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss:SSS");
            writer.write(tTimeFormatter.format(System.currentTimeMillis()) + " name: " + name + " Timestamp: "+ timeStamp);
            writer.newLine();
        } catch (IOException e) {
          System.out.print(e.getStackTrace());
        }
    }

解决方案

You can write to file with StandardOpenOptions: CREATE and APPEND.

Files.write(Paths.get(""), new byte[] {}, StandardOpenOption.CREATE, StandardOpenOption.APPEND);

CREATE - means if file doesn't exists it creates new one otherwise get existing. APPEND - means append new data to existing content in file.

So, you can do all your operations with a single line.

这篇关于Java IO创建/附加文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆