在Java中,可以使用java.io
和java.nio.file
包中的类和方法来实现文件操作。以下是一些常见的文件操作示例:
import java.io.File;
import java.io.IOException;
public class CreateFile {
public static void main(String[] args) {
File file = new File("example.txt");
try {
if (file.createNewFile()) {
System.out.println("File created: " + file.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFile {
public static void main(String[] args) {
File file = new File("example.txt");
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class WriteFile {
public static void main(String[] args) {
File file = new File("example.txt");
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
bw.write("Hello, World!");
System.out.println("Content written to file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
import java.io.File;
public class ListDirectory {
public static void main(String[] args) {
File directory = new File("."); // 当前目录
if (directory.isDirectory()) {
String[] files = directory.list();
if (files != null) {
for (String file : files) {
System.out.println(file);
}
}
} else {
System.out.println("Not a directory.");
}
}
}
import java.io.File;
public class DeleteFile {
public static void main(String[] args) {
File file = new File("example.txt");
if (file.delete()) {
System.out.println("File deleted: " + file.getName());
} else {
System.out.println("File not found or cannot be deleted.");
}
}
}
这些示例展示了如何使用Java进行基本的文件操作。在实际应用中,你可能需要根据具体需求进行调整。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。