1 文件到字节流
1.1 IO
IO:输入流,直接写完close即可
InputStream in = new FileInputStream(fileName);
DataInputStream stream = new DataInputStream(in);
IO:输出流,直接读完close即可,即使FileOutputStream(String name, boolean append)可以有append参数但是这个跟Files相比还是弱
FileOutputStream fileOut = new FileOutputStream(fileName);
DataOutputStream stream = new DataOutputStream(fileOut)
1.2 NIO 借助java.nio.file.Files
NIO:输入流
InputStream in = Files.newInputStream(Paths.get(fileName), StandardOpenOption.READ);
NIO:输出流
OutputStream out = Files.newOutputStream(Paths.get(fileName));//StandardOpenOption.CREATE,没有参数会无视有没有文件存在都trunte并rewrite
2 文件和byte[]
2.1 将byte[]写入文件
Files.write(Paths.get(fileName), data, options);
2.2 从文件获取所有的byte[]
Files.readAllBytes(Paths.get(fileName));
2.3 或者参考
public static byte[] nioRead(String file){
byte[] b = null;
try(FileInputStream in = new FileInputStream(file)) {
FileChannel channel = in.getChannel(); //FileInputStream.getChannel()
ByteBuffer buffer = ByteBuffer.allocate(1024);
channel.read(buffer);
b = buffer.array();
return b;
} catch (Exception e) {
LogCore.BASE.error("nioRead err:{}", e);
return b;
}
}
3 从InputStream流到byte[] is.available()是全部字节码
请看下面代码
public static byte[] readAllBytes(InputStream is){
byte[] data = null;
try {
if(is.available()==0){//返回null而不是空byte[]
return data;
}
data = new byte[is.available()];
is.read(data);
is.close();
return data;
} catch (IOException e) {
e.printStackTrace();
return data;
}
}
注意这个方法只能正确读取本地文件的流is.available()就是全部的字节数。
如果是网络过来的流的话is.available()可就不是全部字节数了,而只是当前可读的字节数
正确的例子如下
思路是不断的读取byte[1024]然后组成新数组byte[total]也就是不断用System.arrayCopy去合并数组
其实这也是字节流的过程!!!
因此下发如下
public boolean save(String filename, String contentType, InputStream is) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
byte[] data = baos.toByteArray();
Files.write(Paths.get(rootPath, filename), data);
is.close();
baos.close();
return true;
} catch (IOException e) {
LogCore.BASE.error("save file err", e);
return false;
}
}
4 字节流和byte[]
- 可以根据这个自定义序列化方案
4.1 字节流写入并提取byte[]
ByteArrayOutputStream bout = new ByteArrayOutputStream();
DataOutputStream stream = new DataOutputStream(bout);
stream.writeInt(v);
...
bout.toByteArray();
4.2 读byte[]数据到字节流
ByteArrayInputStream in = new ByteArrayInputStream(data);
DataInputStream stream = new DataInputStream(in);
int wireFormat = stream.readInt();
...
5 移动文件
Files.move(Paths.get(srcName), Paths.get(tarName));//如果存在java.nio.file.FileAlreadyExistsException
Files.move(Paths.get(srcName), Paths.get(newname), StandardCopyOption.REPLACE_EXISTING);//如果目标文件存在则被替换
5 其他
5.1 判断文件是否存在
Files.exists(Paths.get(fileName));