用最简单的方法,在java中如何创建一个文件并写入内容?
创建一个文本文件:
PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8"); writer.println("The first line"); writer.println("The second line"); writer.close();
创建一个二进制文件:
byte data[] = ... FileOutputStream out = new FileOutputStream("the-file-name"); out.write(data); out.close();
Java 7+用户可以使用Files该类来写入文件:
List<String> lines = Arrays.asList("The first line", "The second line"); Path file = Paths.get("the-file-name.txt"); Files.write(file, lines, StandardCharsets.UTF_8); //Files.write(file, lines, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
byte data[] = ... Path file = Paths.get("the-file-name"); Files.write(file, data); //Files.write(file, data, StandardOpenOption.APPEND);