我如何创建一个文件并在Java中写入? [英] How do I create a file and write to it in Java?

查看:118
本文介绍了我如何创建一个文件并在Java中写入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中创建和写入文本的最简单的方法是什么?

下面的每个代码示例都会抛出 IOExcepions 。 Try / catch / finally块为简洁起见已被省略。有关异常处理的信息,请参阅本教程



创建一个文本文件(注意,如果文件已存在,将覆盖该文件):

  PrintWriter writer = new PrintWriter(the-file-name.txt,UTF-8); 
writer.println(第一行);
writer.println(第二行);
writer.close();

创建二进制文件(也将覆盖文件):

  byte data [] = ... 
FileOutputStream out = new FileOutputStream(the-file-name);
out.write(data);
out.close();用户可以使用



$ b //docs.oracle.com/javase/7/docs/api/index.html?java/nio/file/Files.htmlrel =noreferrer> Files
类写入文件:

创建一个文本文件:

 列表与LT;字符串> lines = Arrays.asList(第一行,第二行); 
Path file = Paths.get(the-file-name.txt);
Files.write(文件,行,Charset.forName(UTF-8));
//Files.write(文件,行,Charset.forName(UTF-8),StandardOpenOption.APPEND);

创建二进制文件:

  byte data [] = ... 
Path file = Paths.get(the-file-name);
Files.write(file,data);
//Files.write(文件,数据,StandardOpenOption.APPEND);


What's the simplest way to create and write to a (text) file in Java?

解决方案

Note that each of the code samples below throw IOExcepions. Try/catch/finally blocks have been omitted for brevity. See this tutorial for information about exception handling.

Creating a text file (note that this will overwrite the file if it already exists):

PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
writer.println("The first line");
writer.println("The second line");
writer.close();

Creating a binary file (will also overwrite the file):

byte data[] = ...
FileOutputStream out = new FileOutputStream("the-file-name");
out.write(data);
out.close();

Java 7+ users can use the Files class to write to files:

Creating a text file:

List<String> 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);

Creating a binary file:

byte data[] = ...
Path file = Paths.get("the-file-name");
Files.write(file, data);
//Files.write(file, data, StandardOpenOption.APPEND);

这篇关于我如何创建一个文件并在Java中写入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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