一,介绍
今天来介绍下java读写文件和压缩功能
二,读
1,读取文件
实际开发中,从磁盘上读取文件一般很少,大多从第三方接口,如http请求获取、网关获取。
获取的结果都是差不多,都是流对象,为了测试方便,代码就从本地获取。
2,代码
/*** 按行读取文件
*@parampath*/
public static voidreadFile(String path){try{
File file= newFile(path);
BufferedReader bufferedReader= new BufferedReader(newFileReader(path));
String strLine= null;int lineCount = 1;while(null != (strLine =bufferedReader.readLine())){
logger.info("第[" + lineCount + "]行数据:[" + strLine + "]");
lineCount++;
}
}catch(Exception e){
e.printStackTrace();
}
}
代码采用的是FileReader,也可以用FileInputStream获取字节
/*** 一次性读取全部文件数据
*@parampath*/
public static voidreadFile(String path){try{
InputStream is= newFileInputStream(path);int len=is.available();byte[] bytes = new byte[len];
is.read(bytes);
logger.info("文件内容:\n" + newString(bytes));
is.close();
}catch(Exception e){
e.printStackTrace();
}
}
三,写
/*** 将文件数据写到磁盘
*@paramoutputStream
*@parampath*/
public static voidoutFile(OutputStream outputStream, String path){try{
FileOutputSteam fileOutStream= newFileOutputStream(path);
fileOutputStream.write(outputStream.toByteArray());
}catch(Exception e){
e.printStackTrace();
}
}
其中outputStream是从inputStream写过来的,比如outputStream.write(inputStream.toByteArray())。
四,压缩
开发中,元数据如果过大,可以考虑压缩数据,java中也提供相关的类,ZipOutputStream
代码:
/*** 压缩文件
*@param*@param
*/
public static voidzipOutFile(String path){
ByteArrayOutputStream outputStream1= newByteArrayOutputStream();
ZipOutputStream zipOutputStream= new ZipOutputStream(outputStream1, Charset.forName("GBK"));
for (int i = 1; i <= 500; i++) {
ByteArrayOutputStream outputStream= newByteArrayOutputStream();
outputStream.write(inputStream.toByteArray());
zipOutputStream.putNextEntry(new ZipEntry("tmp" + name_index + ".csv"));
zipOutputStream.write(outputStream.toByteArray());
zipOutputStream.closeEntry();
name_index++;
}
try{
FileOutputSteam fileOutStream = newFileOutputStream(path);
fileOutputStream.write(outputStream1.toByteArray);
}catch(Exception e){
e.printStackTrace();
}
}
1,代码中outputStream1存放的是zipOutputStream压缩的内容,其中是压缩包,压缩着1、2、3.csv
2,先将读取到的inputStream放到outPutStream,然后压缩outputStream到outputStream1,最后将outputStream1写到磁盘上。
3,实际生产上,一般不会写到本地,直接上传服务器,如持久化网关服务等,为了测试大家看着就行。