📅  最后修改于: 2023-12-03 14:42:17.867000             🧑  作者: Mango
在Java中,我们可以通过File类和相应的输入/输出流来创建包含内容的文件。下面介绍几种创建文件的方法。
import java.io.FileOutputStream;
import java.io.IOException;
public class CreateFileExample {
public static void main(String[] args) {
try {
String content = "This is the content to write into file";
FileOutputStream outputStream = new FileOutputStream("output.txt");
byte[] bytes = content.getBytes();
outputStream.write(bytes);
outputStream.close();
System.out.println("File created successfully!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
上述代码创建了一个名为"output.txt"的文件,并将字符串"This is the content to write into file"写入文件。
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class CreateFileExample {
public static void main(String[] args) {
try {
String content = "This is the content to write into file";
File file = new File("output.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fileWriter = new FileWriter(file);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(content);
bufferedWriter.close();
System.out.println("File created successfully!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
上述代码创建了一个名为"output.txt"的文件,并将字符串"This is the content to write into file"写入文件。
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class CreateFileExample {
public static void main(String[] args) {
try {
String content = "This is the content to write into file";
File file = new File("output.txt");
PrintWriter printWriter = new PrintWriter(file);
printWriter.println(content);
printWriter.close();
System.out.println("File created successfully!");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
上述代码创建了一个名为"output.txt"的文件,并将字符串"This is the content to write into file"写入文件。
以上三种方法均可用于创建包含内容的文件,具体方法可根据自己的需求选择。