在内置的蟒蛇开放的功能,是个什么模式之间准确的区别w,a,w+,a+,和r+?
特别是,文档暗示所有这些都允许写入文件,并说它打开文件"具体"附加",写入"和"更新",但没有定义这些术语的含义.
我试图创建一个文件,如果它不存在,如果它存在则追加到它。这是最好的方法吗?我个人不确定在一个方法中包含两个 try catch 是否好?
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());
}
}
Run Code Online (Sandbox Code Playgroud)