发布日期:2018-03-26
在Java中,如何创建一个文件并对它执行写入操作?+ 查看更多
在Java中,如何创建一个文件并对它执行写入操作?
+ 查看更多
发布日期:2018-03-10 13:33
分类:JAVA
浏览次数:92
在Java中,有什么简单的方法来创建并写入(文本)文件?
回答
创建一个文本文件(请注意,这样会覆盖已经存在的同名文件):
try{ PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8"); writer.println("The first line"); writer.println("The second line"); writer.close(); } catch (IOException e) { // do something }创建一个二进制文件(同样会覆盖文件):
byte data[] = ... FileOutputStream out = new FileOutputStream("the-file-name"); out.write(data); out.close();Java 7版本以上的用户可以用文件类来写入文件:
创建一个文本文件:
List创建一个二进制文件:lines = Arrays.asList("The first line", "The second line"); Path file = Paths.get("the-file-name.txt"); Files.write(file, lines, Charset.forName("UTF-8")); //Files.write(file, lines, Charset.forName("UTF-8"), StandardOpenOption.APPEND);
byte data[] = ... Path file = Paths.get("the-file-name"); Files.write(file, data); //Files.write(file, data, StandardOpenOption.APPEND);