用Java创建和写入(文本)文件的最简单方法是什么?
当前回答
要创建文件而不覆盖现有文件,请执行以下操作:
System.out.println("Choose folder to create file");
JFileChooser c = new JFileChooser();
c.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
c.showOpenDialog(c);
c.getSelectedFile();
f = c.getSelectedFile(); // File f - global variable
String newfile = f + "\\hi.doc";//.txt or .doc or .html
File file = new File(newfile);
try {
//System.out.println(f);
boolean flag = file.createNewFile();
if(flag == true) {
JOptionPane.showMessageDialog(rootPane, "File created successfully");
}
else {
JOptionPane.showMessageDialog(rootPane, "File already exists");
}
/* Or use exists() function as follows:
if(file.exists() == true) {
JOptionPane.showMessageDialog(rootPane, "File already exists");
}
else {
JOptionPane.showMessageDialog(rootPane, "File created successfully");
}
*/
}
catch(Exception e) {
// Any exception handling method of your choice
}
其他回答
我能找到的最简单的方法是:
Path sampleOutputPath = Paths.get("/tmp/testfile")
try (BufferedWriter writer = Files.newBufferedWriter(sampleOutputPath)) {
writer.write("Hello, world!");
}
它可能只适用于1.7+。
public static void writefromFile(ArrayList<String> lines, String destPath) {
FileWriter fw;
try {
fw = new FileWriter(destPath);
for (String str : lines) {
fw.write(str);
}
fw.close();
} catch (IOException ex) {
JOptionPane.showMessageDialog("ERROR: exception was: " + ex.toString());
}
File f = new File(destPath);
f.setExecutable(true);
}
请注意,下面的每个代码示例都可能引发IOException。为了简洁起见,省略了Try/catch/finally块。有关异常处理的信息,请参阅本教程。
请注意,如果文件已经存在,下面的每个代码示例都将覆盖该文件
创建文本文件:
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);
以下是编写文件的代码,也在退出帮助内容网页时删除:
public String writeHelpContent(String filePath, String helpPageContent) throws IOException{
logger.info("HowToUseRiskOfficeHelpService - writeHelpContent start");
File file = new File(filePath);
try(FileWriter fw = new FileWriter(file);){
file.deleteOnExit();
if(file.createNewFile()) {
logger.info("HowToUseRiskOfficeHelpService - file created successfully");
}else {
logger.info("HowToUseRiskOfficeHelpService - file already exists");
}
fw.write(helpPageContent);
fw.flush();
}
return "Sucessfully write into help page file";
}
Java 7+值得一试:
Files.write(Paths.get("./output.txt"), "Information string herer".getBytes());
看起来很有希望。。。
推荐文章
- Java 8接口方法中不允许“同步”的原因是什么?
- 如何找到Java堆大小和内存使用(Linux)?
- 使用Enum实现单例(Java)
- RabbitMQ与通道和连接之间的关系
- buildSessionFactory()配置方法在Hibernate中已弃用?
- Spring MVC -如何获得所有的请求参数在一个地图在Spring控制器?
- 如何在Java中按两个字段排序?
- 文件之间的差异。路径中的分隔符和斜杠
- 在方法参数中使用NotNull注释
- Spring MVC中处理可选参数的@RequestParam
- Tomcat:如何查找正在运行的Tomcat版本?
- 如何在Python中连接文本文件?
- “java”、“javaw”和“javaws”之间有什么区别?
- 将Date对象转换为日历对象
- 在Java中保存最后N个元素的大小有限的队列