import java.io.*;
public class FileOperations {
public static void main(String[] args) {
// 创建目录
File dir = new File("目录");
if (!dir.exists()) {
boolean isCreated = dir.mkdir();
if (isCreated) {
System.out.println("文件创建成功");
} else {
System.out.println("无法创建文件!");
}
}
// 创建文件并写入内容
try (FileWriter writer = new FileWriter("目录/example.txt")) {
writer.write("你好");
System.out.println("已成功输入");
} catch (IOException e) {
e.printStackTrace();
}
// 顺序读取文件内容
try (BufferedReader reader = new BufferedReader(new FileReader("目录/example.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (FileNotFoundException e) {
System.out.println("未找到内容!");
} catch (IOException e) {
e.printStackTrace();
}
// 随机读取文件内容
try (RandomAccessFile file = new RandomAccessFile("目录/example.txt", "rw")) {
file.seek(5); // 移动到索引5的位置
String content = file.readUTF(); // 读取一个以UTF编码的字符串
System.out.println(content); // 输出: "World!"
} catch (FileNotFoundException e) {
System.out.println("未找到内容!");
} catch (IOException e) {
e.printStackTrace();
}
// 读取不存在的文件
try (BufferedReader reader = new BufferedReader(new FileReader("目录/nonexistent.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (FileNotFoundException e) {
System.out.println("未找到文件!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
该段代码的程序流程图是什么