Java IO(输入/输出)库提供了用于处理文件和数据流的类和接口。以下是一些使用Java IO进行文件流操作的技巧:
try (FileInputStream fis = new FileInputStream("file.txt")) {
// 读取文件内容
} catch (IOException e) {
e.printStackTrace();
}
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream("file.txt"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("output.txt"))) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = bis.read(buffer)) != -1) {
bos.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
try (DataInputStream dis = new DataInputStream(new FileInputStream("input.txt"));
DataOutputStream dos = new DataOutputStream(new FileOutputStream("output.txt"))) {
dos.writeInt(42);
dos.writeDouble(3.14);
} catch (IOException e) {
e.printStackTrace();
}
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("object.txt"));
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("output.txt"))) {
MyClass obj = new MyClass();
oos.writeObject(obj);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
try (FileInputStream fis = new FileInputStream("file.txt");
FileChannel inChannel = fis.getChannel()) {
FileChannel outChannel = new FileOutputStream("output.txt").getChannel();
long size = inChannel.size();
long transferred = 0;
while (transferred < size) {
transferred += inChannel.transferTo(transferred, size - transferred, outChannel);
}
} catch (IOException e) {
e.printStackTrace();
}
try (Path inputPath = Paths.get("input.txt");
Path outputPath = Paths.get("output.txt")) {
List<String> lines = Files.readAllLines(inputPath);
Files.write(outputPath, lines);
} catch (IOException e) {
e.printStackTrace();
}
try {
Path source = Paths.get("source.txt");
Path target = Paths.get("target.txt");
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
Path path = Paths.get("file.txt");
System.out.println("File name: " + path.getFileName());
System.out.println("File size: " + path.toFile().length());
try (BufferedWriter writer = Files.newBufferedWriter(Paths.get("output.txt"), StandardOpenOption.CREATE, StandardOpenOption.APPEND)) {
writer.write("Hello, World!");
} catch (IOException e) {
e.printStackTrace();
}
File file = new File("file.txt");
if (!file.exists()) {
file.createNewFile();
}
if (file.delete()) {
System.out.println("File deleted successfully.");
}
这些技巧可以帮助您更有效地使用Java IO进行文件流操作。在实际应用中,您可能需要根据具体需求选择合适的方法。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。