用Java创建和写入(文本)文件的最简单方法是什么?
当前回答
您甚至可以使用系统属性创建临时文件,该属性与您使用的操作系统无关。
File file = new File(System.*getProperty*("java.io.tmpdir") +
System.*getProperty*("file.separator") +
"YourFileName.txt");
其他回答
只有一行!路径和行是字符串
import java.nio.file.Files;
import java.nio.file.Paths;
Files.write(Paths.get(path), lines.getBytes());
如果我们使用的是Java7及以上版本,并且还知道要添加(附加)到文件中的内容,我们可以使用NIO包中的newBufferedWriter方法。
public static void main(String[] args) {
Path FILE_PATH = Paths.get("C:/temp", "temp.txt");
String text = "\n Welcome to Java 8";
//Writing to the file temp.txt
try (BufferedWriter writer = Files.newBufferedWriter(FILE_PATH, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) {
writer.write(text);
} catch (IOException e) {
e.printStackTrace();
}
}
有几点需要注意:
指定字符集编码总是一个好习惯,因此我们在类StandardCharset中有常量。代码使用try with resource语句,其中资源在try之后自动关闭。
虽然OP没有询问,但为了以防万一我们想搜索具有特定关键字的行,例如机密,我们可以使用Java中的流API:
//Reading from the file the first line which contains word "confidential"
try {
Stream<String> lines = Files.lines(FILE_PATH);
Optional<String> containsJava = lines.filter(l->l.contains("confidential")).findFirst();
if(containsJava.isPresent()){
System.out.println(containsJava.get());
}
} catch (IOException e) {
e.printStackTrace();
}
最好的方法是使用Java7:Java7引入了一种处理文件系统的新方法,以及一个新的实用程序类—Files。使用Files类,我们还可以创建、移动、复制、删除文件和目录;它还可以用于读取和写入文件。
public void saveDataInFile(String data) throws IOException {
Path path = Paths.get(fileName);
byte[] strToBytes = data.getBytes();
Files.write(path, strToBytes);
}
使用FileChannel写入如果您正在处理大型文件,FileChannel可以比标准IO更快。以下代码使用FileChannel将字符串写入文件:
public void saveDataInFile(String data)
throws IOException {
RandomAccessFile stream = new RandomAccessFile(fileName, "rw");
FileChannel channel = stream.getChannel();
byte[] strBytes = data.getBytes();
ByteBuffer buffer = ByteBuffer.allocate(strBytes.length);
buffer.put(strBytes);
buffer.flip();
channel.write(buffer);
stream.close();
channel.close();
}
使用DataOutputStream写入
public void saveDataInFile(String data) throws IOException {
FileOutputStream fos = new FileOutputStream(fileName);
DataOutputStream outStream = new DataOutputStream(new BufferedOutputStream(fos));
outStream.writeUTF(data);
outStream.close();
}
使用FileOutputStream写入
现在让我们看看如何使用FileOutputStream将二进制数据写入文件。以下代码转换String int字节,并使用FileOutputStream将字节写入文件:
public void saveDataInFile(String data) throws IOException {
FileOutputStream outputStream = new FileOutputStream(fileName);
byte[] strToBytes = data.getBytes();
outputStream.write(strToBytes);
outputStream.close();
}
使用PrintWriter写入我们可以使用PrintWriter将格式化文本写入文件:
public void saveDataInFile() throws IOException {
FileWriter fileWriter = new FileWriter(fileName);
PrintWriter printWriter = new PrintWriter(fileWriter);
printWriter.print("Some String");
printWriter.printf("Product name is %s and its price is %d $", "iPhone", 1000);
printWriter.close();
}
使用BufferedWriter写入:使用BufferedWriter将字符串写入新文件:
public void saveDataInFile(String data) throws IOException {
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
writer.write(data);
writer.close();
}
将字符串附加到现有文件:
public void saveDataInFile(String data) throws IOException {
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true));
writer.append(' ');
writer.append(data);
writer.close();
}
我认为这是最短的路:
FileWriter fr = new FileWriter("your_file_name.txt"); // After '.' write
// your file extention (".txt" in this case)
fr.write("Things you want to write into the file"); // Warning: this will REPLACE your old file content!
fr.close();
以下是编写文件的代码,也在退出帮助内容网页时删除:
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";
}
推荐文章
- Javadoc @see或{@link}?
- 在准备语句中使用“like”通配符
- Android Eclipse -无法找到*.apk
- javac和Eclipse编译器之间的区别是什么?
- 工厂模式和策略模式之间的区别是什么?
- 在Java中使用正则表达式提取值
- 如何允许所有网络连接类型HTTP和HTTPS在Android(9)馅饼?
- Intellij IDEA Java类在保存时不能自动编译
- 何时使用Mockito.verify()?
- 在maven中安装mvn到底做什么
- 不可变与不可修改的集合
- 如何在JSON中使用杰克逊更改字段名
- GSON -日期格式
- 如何从线程捕获异常
- 无法解析主机"<URL here>"没有与主机名关联的地址