平常写java时,经常会遇到文件相关的操作。文件读写,基本可以概括为从具体文件(File),到流(Stream),最后到字节(byte[ ]),或者反过来。
也就是说文件操作一切都归结为操作字节:
- 读 = 将文件通过流读出字节
- 写 = 将字节通过流写入到文件中
File 与 byte[ ] 的转换
1、把 File 转换为 byte[ ]
/**
*
* @param file 目标文件
* @return bytes file的字节数组
* @throws IOException
*/
private static byte[] getBytesFromFile(File file) throws IOException {
byte[] bytes = null;
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = fis.read(buffer);
while (len!= -1) {
baos.write(buffer, 0, len);
len = fis.read(buffer);
}
bytes = baos.toByteArray();
if(ArrayUtils.isEmpty(bytes)){
System.out.println("byte[]为空");
}else {
System.out.println("byte[]不为空");
}
return bytes;
}
2、byte[ ] 转换为 File
File file = new File("E:/xxx/xxx/alan.jpg");
FileOutputStream fos = new FileOutputStream(file);
fos.write(bytes,0,bytes.length);
文件复制
private static void copyFile(File fileSource,File fileTarget) throws IOException {
FileInputStream fis = null;
BufferedInputStream bis = null;
FileOutputStream fos = new FileOutputStream(fileTarget);
try{
fis = new FileInputStream(fileSource);
bis = new BufferedInputStream(fis);
byte[] buffer = new byte[1024];
int i = bis.read(buffer);
while(i!=-1){
fos.write(buffer,0,i);
i=bis.read(buffer);
}
}catch(Exception e){
e.printStackTrace();
}finally{
bis.close();
fis.close();
fos.close();
}
}
对象与文件
1、把对象写入文件中
File fileTarget = new File("E:/xxx/xxx");
User user = new User();
try (ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream(fileTarget));) {
oos.writeObject(user);
} catch (Exception e) {
System.out.println("写入异常", e);
}
2、把文件内容读进对象里
File file = new File("E:/xxx/xxx");
User user = null;
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
user = (User) ois.readObject();
} catch (Exception e) {
System.out.println("写出异常");
}