用Java创建和写入(文本)文件的最简单方法是什么?
当前回答
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);
}
其他回答
在Java 7及以上版本中:
try (Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("filename.txt"), "utf-8"))) {
writer.write("something");
}
但有一些有用的实用程序:
来自commons io的FileUtils.writeStringtoFile(..)来自番石榴的文件.write(..)
还要注意,您可以使用FileWriter,但它使用默认编码,这通常是一个坏主意-最好显式指定编码。
以下是Java 7之前的原始答案
Writer writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("filename.txt"), "utf-8"));
writer.write("Something");
} catch (IOException ex) {
// Report
} finally {
try {writer.close();} catch (Exception ex) {/*ignore*/}
}
另请参阅:读取、写入和创建文件(包括NIO2)。
要创建文件而不覆盖现有文件,请执行以下操作:
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
}
以下是编写文件的代码,也在退出帮助内容网页时删除:
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";
}
使用Google的Guava库,我们可以创建和写入文件容易地
package com.zetcode.writetofileex;
import com.google.common.io.Files;
import java.io.File;
import java.io.IOException;
public class WriteToFileEx {
public static void main(String[] args) throws IOException {
String fileName = "fruits.txt";
File file = new File(fileName);
String content = "banana, orange, lemon, apple, plum";
Files.write(content.getBytes(), file);
}
}
该示例在项目根目录中创建一个新的fruits.txt文件。
package fileoperations;
import java.io.File;
import java.io.IOException;
public class SimpleFile {
public static void main(String[] args) throws IOException {
File file =new File("text.txt");
file.createNewFile();
System.out.println("File is created");
FileWriter writer = new FileWriter(file);
// Writes the content to the file
writer.write("Enter the text that you want to write");
writer.flush();
writer.close();
System.out.println("Data is entered into file");
}
}
推荐文章
- 在流中使用Java 8 foreach循环移动到下一项
- 访问限制:'Application'类型不是API(必需库rt.jar的限制)
- 用Java计算两个日期之间的天数
- 如何配置slf4j-simple
- 在Jar文件中运行类
- 带参数的可运行?
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 我可以在Java中设置enum起始值吗?
- Java中的回调函数
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 在Java中,流相对于循环的优势是什么?
- Jersey在未找到InjectionManagerFactory时停止工作
- 在Java流是peek真的只是调试?
- Recyclerview不调用onCreateViewHolder
- 将JSON字符串转换为HashMap