1. 使用`File`类:
```java
import java.io.File;
import java.io.IOException;
public class CreateFileExample {
public static void main(String[] args) {
File file = new File("path/to/file.txt");
try {
if (file.createNewFile()) {
System.out.println("File created successfully.");
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
2. 使用`FileOutputStream`类:
```java
import java.io.FileOutputStream;
import java.io.IOException;
public class CreateFileExample {
public static void main(String[] args) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream("example.txt");
fos.write("Hello, world!".getBytes());
System.out.println("File created successfully.");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
3. 使用`BufferedWriter`类:
```java
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class CreateFileExample {
public static void main(String[] args) {
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter("example.txt"));
writer.write("Hello, world!");
System.out.println("File created successfully.");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
4. 使用`Files`类(Java 7及以上版本推荐):
```java
import java.nio.file.Files;
import java.nio.file.Paths;
public class CreateFileExample {
public static void main(String[] args) {
String content = "Hello, world!";
try {
Files.write(Paths.get("example.txt"), content.getBytes());
System.out.println("File created successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}