// ------拷贝操作-------
// 源文件path
File targetFile = new File("/Users/aionyiruma/Desktop/file测试/newnew.txt");
// 副本所在path
File copyFile = new File("/Users/aionyiruma/Desktop/file测试/copy_newnew.txt");
// 拷贝操作
try ( //声明自动关闭变量,省去close操作
InputStream inputStream = new FileInputStream(targetFile);
// true:末尾追加 false:覆盖
OutputStream outputStream = new FileOutputStream(copyFile, false);) {
byte[] targetBytes = new byte[10];
int length = inputStream.read(targetBytes);
while (length != -1) {
// 只要还有数据 就往临时数组里添加 直到返回-1
outputStream.write(targetBytes);
length = inputStream.read(targetBytes);
}
} catch (Exception e) {
e.printStackTrace();
}
// ------读取操作------
try (InputStream inputStream = new FileInputStream(targetFile);) {// 创建一个二进制流数组
byte[] arr = new byte[5];
// 当inputStream.read(arr))方法返回-1时,表示已经读取完毕
int length = -1;
while ((length = inputStream.read(arr)) != -1) {
// 将的unicode编码解析成字符串
String string = new String(arr, 0, length);
System.out.println(string);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
// ------写入操作------
try (OutputStream outputStream = new FileOutputStream(targetFile, true);) {
outputStream.write("1234567".getBytes(), 2, 4);
} catch (Exception e) {
e.printStackTrace();
}
网友评论