字节打印流 - PrintStream
构造方法 | 作用 |
public PrintStream(OutputStream/File/String) | 关联字节输出流/文件/文件路径 |
public PrintStream(String fileName, Charset charset) | 指定字符编码 |
public PrintStream(OutputStream out, boolean autoFlush) | 自动刷新 |
public PrintStream(OutputStream out, boolean autoFlush, String encoding) | 指定字符编码且自动更新 |
字节流底层无缓冲区,自动刷新相当于无效
PrintStream ps = new PrintStream(new FileOutputStream("a.txt"), true, "UTF-8");
ps.println(97);
ps.print(true);
ps.printf("阿正爱上了阿强");
ps.close();
字符打印流
构造方法 | 说明 |
public PrintWriter(Writer) | 关联字节输出流/文件/文件路径 |
public PrintWriter(String filename, Charset charset) | 指定字符编码 |
public PrintWriter(Write w, boolean autoFlush) | 自动刷新 |
public PrintWriter(OutputStream out, boolean autoFlush, Charset charset) | 自定字符编码且自动刷新 |
PrintWriter pw = new PrintWriter(new FileWriter("a.txt"), true);
pw.println("行行好吧,我是做Java的");
pw.print("给口饭吃吧");
pw.printf("听我说谢谢%s", "你");
pw.close();
解压缩流
实质:将ZipEntry对象按照层级目录读取到本地文件中
public static void unzip(File src, File dest) throws IOException {
ZipInputStream zis = new ZipInputStream(new FileInputStream(src));
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
if (entry.isDirectory()) {
File file = new File(dest, entry.toString());
file.mkdirs();
} else {
FileOutputStream fos = new FileOutputStream(new File(dest, entry.toString()));
int len;
while ((len = zis.read()) != -1) {
fos.write(len);
}
fos.close();
zis.closeEntry();
}
}
zis.close();
}
压缩流
压缩单个文件
public static void toZip(File src, File dest) throws IOException {
//创建压缩流关联压缩包
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(new File(dest, "a.zip")));
//创建ZipEntry对象表示压缩包里面的每一个文件
ZipEntry zn = new ZipEntry("a.txt");
//把ZipEntry对象放到压缩包中
zos.putNextEntry(zn);
//把文件中的数据写到压缩包中
FileInputStream fis = new FileInputStream(src);
int len;
while ((len = fis.read()) != -1) {
zos.write(len);
}
zos.closeEntry();
zos.close();
}
压缩整个文件夹
public static void main(String[] args) throws IOException {
File src = new File("a");
File destParents = src.getParentFile();
File dest = new File(destParents, src.getName() + ".zip");
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(dest));
toZip(src, zos, src.getName());
zos.close();
}
public static void toZip(File src, ZipOutputStream zos, String name) throws IOException {
File[] files = src.listFiles();
for (File file : files) {
if (file.isFile()) {
ZipEntry zip = new ZipEntry(name + "\\" + file.getName());
zos.putNextEntry(zip);
FileInputStream fis = new FileInputStream(file);
int b;
while ((b = fis.read()) != -1) {
zos.write(b);
}
fis.close();
zos.closeEntry();
} else {
toZip(file, zos, name + "\\" + file.getName());
}
}
}
Commons-io
一个提高IO流工作效率的工具包
使用步骤
在项目中创建一个文件夹:lib
将jar包复制粘贴到lib文件夹
右键点击jar包,选择Add as Library -> 点击OK
在类中导包使用