7.2 字节流
实例123 复制指定目录下的文件
package Chapter07.stream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import Chapter07.file.FileDemo_05;
public class StreamDemo_01 {
// 复制文件,并检察是否复制成功,如果复制成功,则返回true,否则返回false
public static boolean copy_File(String sourceFileName,
String targetFileName, boolean overlay) {
// 判断原文件是否存在
File srcFile = new File(sourceFileName);
if (!srcFile.exists()) {
System.out.println("复制文件失败:原文件" + sourceFileName + "不存在!");
return false;
} else if (!srcFile.isFile()) {
System.out.println("复制文件失败:" + sourceFileName + "不是一个文件!");
return false;
}
// 判断目标文件是否存在
File targetFile = new File(targetFileName);
if (targetFile.exists()) {
// 如果目标文件已存在且允许覆盖, 删除已存在的目标文件,无论目标文件是目录还是单个文件
if (overlay) {
System.out.println("文件已存在,正删除!");
if (!FileDemo_05.deleteAnyone(targetFileName)) {
System.out.println("删除文件" + targetFileName + "失败!");
return false;
}
} else {
System.out.println("复制文件失败:文件" + targetFileName + "已存在!");
return false;
}
} else {
if (!targetFile.getParentFile().exists()) {
// 如果目标文件所在的目录不存在,则创建目录
System.out.println("目标文件所在的目录不存在,准备创建它!");
if (!targetFile.getParentFile().mkdirs()) {
System.out.println("复制文件失败:创建目标文件所在的目录失败!");
return false;
}
}
}
int byteread = 0; // 读取文件的字节数
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(srcFile); // 创建原文件的输入流
out = new FileOutputStream(targetFile);// 创建原文件的输出流
byte[] buffer = new byte[1024];
// 一次读取1024个字节,当byteread为-1时表示文件已经读完
while ((byteread = in.read(buffer)) != -1) {
out.write(buffer, 0, byteread); // 将读取的字节写入输出流
}
System.out.println("复制文件" + sourceFileName + "至" + targetFileName
+ "成功!");
return true;
} catch (Exception e) {
System.out.println("复制文件失败:" + e.getMessage());
return false;
} finally {
// 关闭输入输出流,注意先关闭输出流,再关闭输入流
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
// 复制整个目录的内容,并判断是否复制成功,如果复制成功返回true,否则返回false
public static boolean copy_Dir(String sourceDirName, String targetDirName,
boolean overlay) {
// 判断原目录是否存在
File sourceDir = new File(sourceDirName);
if (!sourceDir.exists()) {
System.out.println("复制目录失败:原目录" + sourceDirName + "不存在!");
return false;
} else if (!sourceDir.isDirectory()) {
System.out.println("复制目录失败:" + sourceDirName + "不是一个目录!");
return false;
}
// 如果目标文件夹名不以文件分隔符结尾,自动添加文件分隔符
if (!targetDirName.endsWith(File.separator)) {
targetDirName = targetDirName + File.separator;
}
File targetDir = new File(targetDirName);
// 如果目标文件夹存在且允许覆盖时,则删除已存在的目标目录
if (targetDir.exists()) {
if (overlay) {
System.out.println("目录已存在,准备删除它!");
if (!FileDemo_05.deleteAnyone(targetDirName)) {
System.out.println("复制失败:目录" + targetDirName + "已存在!");
}
} else {
System.out.println("复制失败:目录" + targetDirName + "已存在!");
return false;
}
} else {
// 如果目录不存在则创建目标目录
System.out.println("目录不存在,正在创建!");
if (!targetDir.mkdirs()) {
System.out.println("创建目录失败!");
return false;
}
}
boolean flag = true;
// 列出源文件夹下所有文件(包括子目录)的文件名
File[] files = sourceDir.listFiles();
for (int i = 0; i < files.length; i++) {
// 如果是一个文件,则进行复制
if (files[i].isFile()) {
flag = StreamDemo_01.copy_File(files[i].getAbsolutePath(),
targetDirName + files[i].getName(), false);
if (!flag) {
break;
}
}
// 如果是子目录,继续复制目录
if (files[i].isDirectory()) {
flag = StreamDemo_01.copy_Dir(files[i].getAbsolutePath(),
targetDirName + files[i].getName(), false);
if (!flag) {
break;
}
}
}
if (!flag) {
System.out.println("复制目录" + sourceDirName + "到" + targetDirName
+ "失败!");
return false;
}
System.out
.println("复制目录" + sourceDirName + "到" + targetDirName + "成功!");
return true;
}
public static void main(String[] args) {
String sourcePath = "D:/temp/a1.txt";
String targetPath = "D:/temp0/a1.txt";
// 复制文件,如果目标存在,则覆盖
StreamDemo_01.copy_File(sourcePath, targetPath, true);
// 如果目标存在,则不覆盖
StreamDemo_01.copy_File(sourcePath, targetPath, false);
System.out.println();
String sourceDir = "D:/temp";
String targetDir = "E:/temp";
// 复制文件夹,如果目标存在,则覆盖
StreamDemo_01.copy_Dir(sourceDir, targetDir, true);
}
}
实例124 显示文件中的内容
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
class as {
public static void main(String[] args){
int i=0;
FileInputStream fis = null;
try {
fis=new FileInputStream("d:/sd.txt"); //指定一个文件
} catch (FileNotFoundException e) {
System.out.println("没有找到指定的文件。"); //如果没有找到文件,捕获异常
System.exit(-1);
}catch (ArrayIndexOutOfBoundsException e){
System.exit(-2);
}
try {
while((i=fis.read())!=-1) //循环遍历文件内容
System.out.print((char)i); //输出文件里的内容
fis.close();
} catch (IOException e) {
System.out.println("显示文件名");
}
}
}
实例125 将数据保存到指定的文件中
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
class Number {
public static void main(String[] args) {
try {
OutputStream os = new FileOutputStream("D:/fibonacci.dat");//创建一个文件
DataOutputStream dos = new DataOutputStream(os);
int k = 0, i = 1, j = 1;
for (k = 0; k < 20; k++) {
try {
dos.writeInt(i); //将一个 int 值以 4-byte 值形式写入基础输出流中,先写入高字节。
} catch (IOException e) {
e.printStackTrace();
}
int in = i + j;
i = j;
j = in;
}
try {
os.close(); // 关闭文件输出流
} catch (IOException e) {
System.out.println(e);// 输出异常
}
} catch (FileNotFoundException e) {
System.out.println("文件创建成功!");
}
}
}
实例126 将由键盘中录入的信息保存到文件中
package Chapter07.stream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class StreamDemo_04 {
// 将由键盘中输入的内容保存在指定的文件中
public static boolean saveMessageToFile(String fileName) {
File file = new File(fileName);
// 将数据按照文本输出到文件
PrintWriter pw = null;
BufferedReader in = null;
try {
// 为输出文件建立一个写入器
pw = new PrintWriter(new FileWriter(file));
System.out.println("请输入文件的内容并输入end结束");
// 用BufferedReader包装标准输入流
in = new BufferedReader(new InputStreamReader(System.in));
String inputLine = null;
while (((inputLine = in.readLine()) != null)
&& (!inputLine.equals("end"))) {
pw.println(inputLine);
}
pw.flush();
pw.close();
return true;
} catch (IOException e) {
System.out.println(e.getMessage());
return false;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
// 按照文件中格式将文件内容显示出来
public static void readFileMessage(String fileName) {
File file = new File(fileName);
BufferedReader reader = null;
try {
System.out.println("按顺序读取文件的内容如下:");
reader = new BufferedReader(new FileReader(file));
String string = null;
int line = 1;
// 按行读取内容,直到读入null则表示读取文件结束
while ((string = reader.readLine()) != null) {
System.out.println("line " + line + ": " + string);
line++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
}
public static void main(String[] args) {
String fileName = "D:/temp/qq.txt";
StreamDemo_04.saveMessageToFile(fileName);
System.out.println();
System.out.println("输出文件的内容:");
StreamDemo_04.readFileMessage(fileName);
}
}
实例127 一个文件变成多个小文件
package Chapter07.stream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
public class StreamDemo_05 {
public static final String SUFFIX = ".txt"; // 分割后的文件名后缀
// 将指定的文件按着给定的文件的字节数进行分割文件,其中name指的是需要进行分割的文件名,size指的是指定的小文件的大小
public static String[] divide(String name, long size) throws Exception {
File file = new File(name);
if (!file.exists() || (!file.isFile())) {
throw new Exception("指定文件不存在!");
}
// 获得被分割文件父文件,将来被分割成的小文件便存在这个目录下
File parentFile = file.getParentFile();
// 取得文件的大小
long fileLength = file.length();
if (size <= 0) {
size = fileLength / 2;
}
// 取得被分割后的小文件的数目
int num = (fileLength % size != 0) ? (int) (fileLength / size + 1)
: (int) (fileLength / size);
// 存放被分割后的小文件名
String[] fileNames = new String[num];
// 输入文件流,即被分割的文件
FileInputStream in = new FileInputStream(file);
// 读输入文件流的开始和结束下标
long end = 0;
int begin = 0;
// 根据要分割的数目输出文件
for (int i = 0; i < num; i++) {
// 对于前num - 1个小文件,大小都为指定的size
File outFile = new File(parentFile, file.getName() + i + SUFFIX);
// 构建小文件的输出流
FileOutputStream out = new FileOutputStream(outFile);
// 将结束下标后移size
end += size;
end = (end > fileLength) ? fileLength : end;
// 从输入流中读取字节存储到输出流中
for (; begin < end; begin++) {
out.write(in.read());
}
out.close();
fileNames[i] = outFile.getAbsolutePath();
}
in.close();
return fileNames;
}
public static void readFileMessage(String fileName) {// 将分割成的小文件中的内容读出
File file = new File(fileName);
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String string = null;
// 按行读取内容,直到读入null则表示读取文件结束
while ((string = reader.readLine()) != null) {
System.out.println(string);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
}
public static void main(final String[] args) throws Exception {
String name = "D:/temp/M_Conversion.java";
long size = 521;
String[] fileNames = StreamDemo_05.divide(name, size);
System.out.println("文件" + name + "分割的结果如下:");
for (int i = 0; i < fileNames.length; i++) {
System.out.println(fileNames[i] + "的内容如下:");
StreamDemo_05.readFileMessage(fileNames[i]);
System.out.println();
}
}
}
实例128 多个小文件合成一个文件
package Chapter07.stream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
public class StreamDemo_06 {
// 将多个文件合成一个文件,其中fileNames是一个字符串数组,包括了所有参加合并操作的文件的全路径,TargetFileName指的是合成后的文件的全路径
public static void merge(String[] fileNames, String TargetFileName)
throws Exception {
File fin = null;
// 构建文件输出流
File fout = new File(TargetFileName);
FileOutputStream out = new FileOutputStream(fout);
for (int i = 0; i < fileNames.length; i++) {
// 打开文件输入流
fin = new File(fileNames[i]);
FileInputStream in = new FileInputStream(fin);
// 从输入流中读取数据,并写入到文件数出流中
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
in.close();
}
out.close();
System.out.println("合并文件" + TargetFileName + "中的内容如下:");
}
public static void readFileMessage(String fileName) {// 将合成的文件中的内容读出
File file = new File(fileName);
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String string = null;
// 按行读取内容,直到读入null则表示读取文件结束
while ((string = reader.readLine()) != null) {
System.out.println(string);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
}
public static void main(final String[] args) throws Exception {
// 合并文件
String[] fileNames = { "D:/temp/1.txt", "D:/temp/2.txt",
"D:/temp/3.txt", "D:/temp/4.txt" };
String newFileName = "D:/temp/total.txt";
StreamDemo_06.merge(fileNames, newFileName);
StreamDemo_06.readFileMessage(newFileName);
}
}
实例129 统计指定文件中的字符个数
package Chapter07.stream;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.StreamTokenizer;
public class StreamDemo_07 {
// 统计指定文件中的字符的总数,其中:fileName指的是文件的全路径
public static long xermote(String fileName) {
FileReader reader = null;
try {
reader = new FileReader(fileName);
// 创建分析给定字符流的标记生成器
StreamTokenizer stn = new StreamTokenizer(
new BufferedReader(reader));// 根据给定的字符流创建标记生成器stn
// 下面指定单引号、双引号和注释的转义字符在此标记生成器中是普通字符,不代表其他的特殊的含义
stn.ordinaryChar('\'');
stn.ordinaryChar('\"');
stn.ordinaryChar('/');
// 创建可以统计字符总数的各个变量
String str;
int num_sum = 0;// 用于统计数字字符总数的变量
int word_sum = 0;// 用于统计字母、汉字等字符总数的变量
int sym_sum = 0;// 用行统计标点符号等字符总数的变量
int sum = 0;// 用于计算全部种类字符总数的变量
// 当生成器的下一个标记不是流末尾的常量
while (stn.nextToken() != StreamTokenizer.TT_EOF) {
switch (stn.ttype) {// 来判断当前获取的流的标记类型
// TT_EOL指示已读到行末尾的常量。
case StreamTokenizer.TT_EOL:
break;
// TT_NUMBER指示已读到一个数字标记的常量
case StreamTokenizer.TT_NUMBER:
str = String.valueOf((stn.nval));// stn.nval表示此数字标记的值
num_sum += str.length();
break;
// TT_WORD指示已读到一个文字标记的常量
case StreamTokenizer.TT_WORD:
str = stn.sval;// stn.sval表示此文字标记的值
word_sum += str.length();
break;
default:
// 如果以上3中类型都不是,则为英文的标点符号
str = String.valueOf((char) stn.ttype);
sym_sum += str.length();
}
}
System.out.println("数字标记的和为:" + num_sum);
System.out.println("文字标记的和为: " + word_sum);
System.out.println("标点符号标记的和为: " + sym_sum);
sum = sym_sum + num_sum + word_sum;
System.out.println("此文件中的字符总数为: " + sum);
return sum;
} catch (Exception e) {
e.printStackTrace();
return -1;
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
}
public static void main(String[] args) {
String fileName = "D:/temp/2.txt";
System.out.println("统计文件" + fileName + "中的字符数的结果如下:");
StreamDemo_07.xermote(fileName);
}
}
实例130 对象的序列化与反序列化
package Chapter07.stream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Calendar;
public class StreamDemo_08 {
// 将对象序例化
public static void serialize(String fileName) throws Exception {
// 创建一个对象输出流,将对象输出到文件
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(
fileName));
out.writeObject("Today's date and time as follows:"); // 序列化一个字符串对象到文件
out.writeObject(Calendar.getInstance());// 序列化当前日期对象到文件
// 序列化一个MyClass对象
TestClass tc = new TestClass(1, 2, 3, 4);
out.writeObject(tc);
out.close();
}
// 将序列化的对象反序列
public static void deserialize(String fileName) throws Exception {
// 创建一个对象输入流,从文件读取对象
ObjectInputStream in = new ObjectInputStream(new FileInputStream(
fileName));
// 读取字符串对象
String today = (String) (in.readObject());
System.out.println(today);
// 读日历Calendar对象
Calendar date = (Calendar) (in.readObject());
System.out.println(date.get(Calendar.YEAR) + "年"
+ (date.get(Calendar.MONTH) + 1) + "月"
+ date.get(Calendar.DAY_OF_MONTH) + "日:"
+ date.getTime().toLocaleString());
// 从输入流中读取TestClass对象。
TestClass tc = (TestClass) (in.readObject());
System.out.println(tc.toString());
in.close();
}
public static void main(String[] args) {
System.out.println("反序列化的结果如下:");
String fileName = "D:/temp/TestClass.txt";
try {
StreamDemo_08.serialize(fileName);
} catch (Exception e) {
System.out.println("对象序列化失败" + e.getMessage());
}
try {
StreamDemo_08.deserialize(fileName);
} catch (Exception e) {
System.out.println("对象反序列化失败" + e.getMessage());
}
}
}
// 一个类,用于被序列化和反序列化。 一定要实现Serializable才能够被序列化和反序列化。
class TestClass implements Serializable {
private int m, n; // 一般的实例变量会被序列化和反序列化
private transient int x; // 用transient声明的变量不会被序列化和反序列化
private static int y; // 类变量也不会被序列化和反序列化
public TestClass(int m, int n, int x, int y) {// 利用构造方法赋值
this.m = m;
this.n = n;
this.x = x;
TestClass.y = y;
}
public String toString() {
return m + " : " + n + " :" + x + " :" + y;
}
}
实例131 同时显示多个文件
package Chapter07.stream;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.SequenceInputStream;
import java.util.Enumeration;
public class StreamDemo_10 implements Enumeration {
String filesList[];// 创建一个字符串数组,装所有文件名的全路径
int num = 0; // 记载读取后文件的个数
public StreamDemo_10(String fileslist[]) {
filesList = fileslist;
}
public boolean hasMoreElements() {// 判断是否有可提供使用的元素,有则返回true,否则返回false
if (filesList == null)
return false;
if (num < filesList.length)
return true;
else
return false;
}
public Object nextElement() {// 返回下一个可用的元素
FileInputStream in = null;
if (!hasMoreElements())
return null;
try {
in = new FileInputStream(filesList[num]);// 将该元素加到输入流中
++num;
} catch (FileNotFoundException e) {
System.err.println("打开文件" + filesList[num] + "错误!");
}
return in;
}
public static void main(String args[]) {
StreamDemo_10 myList = new StreamDemo_10(args);
SequenceInputStream sin;
FileOutputStream fout;
int data;
try {
sin = new SequenceInputStream(myList);// 创建SequenceInputStream对象
fout = new FileOutputStream(FileDescriptor.out);// 创建FileOutputStream对象
while ((data = sin.read()) != -1) {
fout.write(data);// 将输入流中的信息写出
}
sin.close();
} catch (FileNotFoundException e) {
System.out.println("文件无法打开!");
} catch (IOException e) {
System.out.println("读写文件有误!");
}
}
}
实例132 生成zip压缩文件
package Chapter07.stream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class StreamDemo_11 {
// 压缩文件或者目录,其中:dirPath:压缩的根目录,srcName:
// dirPath目录下的所有文件包名子目录,targetName:压缩后的zip文件
public static void compressAllZip(String dirPath, String srcName,
String targetName) {
if (dirPath == null) {// 判断根目录是否存在
System.out.println("压缩失败" + dirPath + "目录不存在");
return;
}
File baseDir = new File(dirPath);// 判断dirPath是不是目录
if (!baseDir.exists() || (!baseDir.isDirectory())) {
System.out.println("压缩失败" + dirPath + "目录不存在");
return;
}
String basicRootDir = baseDir.getAbsolutePath();
File targetFile = new File(targetName);// 创建zip文件
try {
// 创建一个zip输出流来压缩数据并写入到zip文件
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
targetFile));
if (srcName.equals("*")) {
// 将baseDir目录下的所有文件压缩到ZIP
StreamDemo_11.compressDirToZip(basicRootDir, baseDir, out);
} else {
File file = new File(baseDir, srcName);
if (file.isFile()) {
StreamDemo_11.compressFileToZip(basicRootDir, file, out);
} else {
StreamDemo_11.compressDirToZip(basicRootDir, file, out);
}
}
out.close();
System.out.println("文件压缩成功,压缩包的文件名为:" + targetName);
} catch (IOException e) {
System.out.println("压缩失败:" + e);
e.printStackTrace();
}
}
// 利用ZipOutputStream对目录的压缩
private static void compressDirToZip(String basicRootDir, File dir,
ZipOutputStream out) {
if (dir.isDirectory()) {
// 列出dir目录下所有文件
File[] files = dir.listFiles();
// 如果是空文件夹
if (files.length == 0) {
ZipEntry entry = new ZipEntry(getFileName(basicRootDir, dir));
// 存储目录信息
try {
out.putNextEntry(entry);
out.closeEntry();
} catch (IOException e) {
e.printStackTrace();
}
return;
}
for (int i = 0; i < files.length; i++) {
if (files[i].isFile()) {
// 如果是文件,调用compressFileToZip方法
StreamDemo_11
.compressFileToZip(basicRootDir, files[i], out);
} else {
// 如果是目录,递归调用
StreamDemo_11.compressDirToZip(basicRootDir, files[i], out);
}
}
}
}
// 利用ZipOutputStream对文件的压缩
private static void compressFileToZip(String basicRootDir, File file,
ZipOutputStream out) {
FileInputStream in = null;
ZipEntry entry = null;
// 创建复制缓冲区
byte[] buffer = new byte[4096];
int bytes_read;
if (file.isFile()) {
try {
in = new FileInputStream(file); // 创建一个文件输入流
// 根据压缩文件的名字构造一个ZipEntry对象,此类表示zip包中的文件条目
entry = new ZipEntry(getFileName(basicRootDir, file));
out.putNextEntry(entry); // 存储项信息到压缩文件
// 将文件的内容通过字节数组复制到压缩文件中
while ((bytes_read = in.read(buffer)) != -1) {
out.write(buffer, 0, bytes_read);
}
out.closeEntry();
in.close();
System.out
.println("添加文件" + file.getAbsolutePath() + "到ZIP文件中!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 获取等待压缩的文件的文件名,例如:D:\tu\1.jpg获取的文件名为tu\1.jpg
private static String getFileName(String basicRootDir, File file) {
if (!basicRootDir.endsWith(File.separator)) {
basicRootDir += File.separator;
}
String filePath = file.getAbsolutePath();
// 对于目录,必须在entry名字后面加上"/",表示它将以目录项存储。
if (file.isDirectory()) {
filePath += "/";
}
int index = filePath.indexOf(basicRootDir);
return filePath.substring(index + basicRootDir.length());
}
public static void main(String[] args) {
// 压缩D盘下的tu目录,压缩后的文件是D:/图片.zip
String dirPath = "D:/";
String srcName = "tu/";
String zipFileName = "D:/test/图片.zip";
StreamDemo_11.compressAllZip(dirPath, srcName, zipFileName);
}
}
实例133 解压缩zip文件
package Chapter07.stream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class StreamDemo_12 {
public static void main(String[] args) {
// 将刚创建的图片.zip文件解压缩到D盘的temp目录下
String fileName = "D:/test";
String zipName = "D:/test/图片.zip";
StreamDemo_12.upzipFile(zipName, fileName);
}
// 将指定的zip文件解压到targetDirName目录下,其中:zipName:zip包的文件名,targetDirName:需解压到的目录
public static void upzipFile(String zipName, String targetDirName) {
if (!targetDirName.endsWith(File.separator)) {
targetDirName += File.separator;
}
try {
// 根据zip文件创建ZipFile对象,此类的作用是从zip文件读取条目。
ZipFile zipFile = new ZipFile(zipName);
ZipEntry zn = null;
String entryName = null;
String targetFileName = null;
byte[] buffer = new byte[4096];
int bytes_read;
// 获取ZIP文件里所有的文件条目的名字
Enumeration entrys = zipFile.entries();
// 循环遍历所有的文件条目的名字
while (entrys.hasMoreElements()) {
zn = (ZipEntry) entrys.nextElement();
// 获得每一条文件的名字
entryName = zn.getName();
targetFileName = targetDirName + entryName;
if (zn.isDirectory()) {
// 如果zn是一个目录,则创建目录
new File(targetFileName).mkdirs();
continue;
} else {
// 如果zn是一个文件,则创建父目录
new File(targetFileName).getParentFile().mkdirs();
}
// 否则创建文件
File targetFile = new File(targetFileName);
System.out.println("正在创建文件:" + targetFile.getAbsolutePath());
// 打开文件输出流
FileOutputStream os = new FileOutputStream(targetFile);
// 从ZipFile对象中打开entry的输入流
InputStream is = zipFile.getInputStream(zn);
while ((bytes_read = is.read(buffer)) != -1) {
os.write(buffer, 0, bytes_read);
}
// 关闭流
os.close();
is.close();
}
System.out.println("解压缩"+zipName+"成功!");
} catch (IOException err) {
System.err.println("解压缩"+zipName+"失败: " + err);
}
}
}
实例134 生成Excel文件
package Chapter07.stream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.Region;
//创建Excel文件
public class StreamDemo_13 {
// 新建一个Excel文件,里面添加5行5列的内容,另外添加一个合并2行5列的大单元格以及一个合并2行1列的5个合并单元格。
public void createExcel(String fileName) {
File file = new File(fileName);// 创建excel文件对象
FileOutputStream fOut = null;
try {
// 创建一个新的HSSFWorkbook对象
HSSFWorkbook workbook = new HSSFWorkbook();
// 创建一个Excel的工作表,可以指定工作表的名字
HSSFSheet sheet = workbook.createSheet("myFirstExcel");
// 创建字体,红色、粗体
HSSFFont font = workbook.createFont();
font.setColor(HSSFFont.COLOR_RED);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
HSSFFont font1 = workbook.createFont();
// 创建字体,黑色、非粗体
font1.setColor(HSSFFont.COLOR_NORMAL);
font1.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
// 创建单元格的格式,如居中、左对齐等
HSSFCellStyle cellStyle = workbook.createCellStyle();
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 水平方向上居中对齐
// 垂直方向上居中对齐
cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
cellStyle.setFont(font); // 设置字体
HSSFCellStyle cellStyle1 = workbook.createCellStyle();
cellStyle1.setAlignment(HSSFCellStyle.ALIGN_LEFT);
cellStyle1.setFont(font1);
// 下面将建立一个4行3列的表。第一行为表头。
int rowNum = 0;// 行标
int colNum = 0;// 列标
// 建立表头信息
HSSFRow row = sheet.createRow((short) rowNum); // 在索引0的位置创建行
HSSFCell cell = null; // 单元格
for (colNum = 0; colNum < 5; colNum++) {
// 在当前行的colNum列上创建单元格
cell = row.createCell((short) colNum);
// 定义单元格为字符类型,也可以指定为日期类型、数字类型
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
// 定义编码方式,为了支持中文,这里使用了ENCODING_UTF_16
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellStyle(cellStyle); // 为单元格设置格式
cell.setCellValue("表头-第" + (colNum + 1) + "列"); // 添加内容至单元格
}
rowNum++;
for (; rowNum < 5; rowNum++) {
// 新建第rowNum行
row = sheet.createRow((short) rowNum);
for (colNum = 0; colNum < 5; colNum++) {
// 在当前行的colNum位置创建单元格
cell = row.createCell((short) colNum);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellStyle(cellStyle1);
cell.setCellValue("表体-第" + rowNum + "行第" + (colNum + 1)
+ "列");
}
}
// 合并单元格
// 先创建2行5列的单元格,然后将这些单元格合并为2个大单元格
rowNum = 5;
for (; rowNum < 9; rowNum++) {
row = sheet.createRow((short) rowNum);
for (colNum = 0; colNum < 5; colNum++) {
// 在当前行的colNum位置创建单元格
cell = row.createCell((short) colNum);
}
}
// 建立第一个大单元格,高度为2,宽度为2
rowNum = 5;
colNum = 0;
Region region = new Region(rowNum, (short) colNum, (rowNum + 1),
(short) (colNum + 4));
sheet.addMergedRegion(region);
// 获得第一个大单元格
cell = sheet.getRow(rowNum).getCell((short) colNum);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellStyle(cellStyle);
cell.setCellValue("合并行单元格");
// 建立第二个大单元格,高度为2,宽度为3
rowNum = 7;
for (colNum = 0; colNum < 5; colNum++) {
region = new Region(rowNum, (short) colNum, (rowNum + 1),
(short) (colNum));
sheet.addMergedRegion(region);
// 获得第二个大单元格
cell = sheet.getRow(rowNum).getCell((short) colNum);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellStyle(cellStyle);
cell.setCellValue("合并列单元格");
}
// 新建一输出文件流
fOut = new FileOutputStream(file);
// 将创建的内容写到指定的Excel文件中
workbook.write(fOut);
fOut.flush();
fOut.close();// 操作结束,关闭文件
System.out.println("Excel文件创建成功!\nExcel文件的存放路径为:"
+ file.getAbsolutePath());
} catch (Exception e) {
System.out.println("Excel文件" + file.getAbsolutePath()
+ "创建失败\n其原因为:" + e);
} finally {
if (fOut != null) {
try {
fOut.close();
} catch (IOException e1) {
}
}
}
}
public static void main(String[] args) throws Exception {
StreamDemo_13 excel = new StreamDemo_13();
String fileName = "D:/temp/new.xls";
excel.createExcel(fileName);
}
}
实例135 读取Excel文件中的内容
package Chapter07.stream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class StreamDemo_14 {
/** 读Excel文件内容 */
public void showExcel(String excelName) {
File file = new File(excelName);
FileInputStream in = null;
try {
// 创建对Excel工作簿文件的引用
in = new FileInputStream(file);
HSSFWorkbook hwb = new HSSFWorkbook(in);
HSSFSheet sheet = hwb.getSheet("myFirstExcel");// 根据指定的名字来引用此Excel中的有效工作表
// 读取Excel 工作表的数据
System.out.println("下面是Excel文件" + file.getAbsolutePath() + "的内容:");
HSSFRow row = null;
HSSFCell cell = null;
int rowNum = 0; // 行标
int colNum = 0; // 列标
for (; rowNum < 9; rowNum++) {
// 获取第rowNum行
row = sheet.getRow((short) rowNum);
for (colNum = 0; colNum < 5; colNum++) {
cell = row.getCell((short) colNum);// 根据当前行的位置来创建一个单元格对象
System.out.print(cell.getStringCellValue() + "\t");// 获取当前单元格中的内容
}
System.out.println(); // 换行
}
in.close();
} catch (Exception e) {
System.out
.println("读取Excel文件" + file.getAbsolutePath() + "失败:" + e);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e1) {
}
}
}
}
public static void main(String[] args) {
StreamDemo_14 excel = new StreamDemo_14();
String excelName = "D:/temp/new.xls";
excel.showExcel(excelName);
}
}
实例136 生成PDF文件
package Chapter07.stream;
import java.awt.Color;
import java.io.*;
import com.lowagie.text.*;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfWriter;
public class StreamDemo_15 {
// 生成PDF文件中的内容
public void creatPDF(String fileName) {
File file = new File(fileName);
FileOutputStream out = null;
try {
Document document = new Document(PageSize.A4, 50, 50, 50, 50);// 实例化文档对象
out = new FileOutputStream(file);
PdfWriter writer = PdfWriter.getInstance(document, out);// 创建写入器
document.open();// 打开文档准备写入内容
// 设置可以在PDF中输入汉字的字体
BaseFont bfChinese = BaseFont.createFont(
"C:\\WINDOWS\\Fonts\\SIMHEI.TTF", BaseFont.IDENTITY_H,
BaseFont.EMBEDDED);
Font font = new Font(bfChinese, 16, Font.BOLD);
font.setColor(0, 0, 255);
Paragraph paragraph1 = new Paragraph("第7章 IO——输入输出流", font);// 创建段落对象
// 创建了一个章节对象,标题为"第7章 IO——输入输出流"
Chapter chapter1 = new Chapter(paragraph1, 0);
// 将编号级别设为 0 就不会在页面上显示章节编号
chapter1.setNumberDepth(0);
Font font1 = new Font(bfChinese, 14, Font.BOLD);
font1.setColor(255, 0, 0);
Paragraph section1_title1 = new Paragraph("7.1 什么是对象序列化?", font1);// 创建小节对象的标题
Section section1 = chapter1.addSection(section1_title1);// 创建小节对象
Font font2 = new Font(bfChinese, 12, Font.NORMAL);
font2.setColor(0, 0, 0);
Paragraph text = new Paragraph("什么是对象序列化呢?简单的说,就是将对象写入流,\n"
+ "而序列化解体则指从流中获取数据后,重构对象的过程。\n"
+ "Java的对象可以分为可序列化对象和不可序列化对象,\n"
+ "从说明文档中,可以看到只有实现了\"Serializable\"接口的对象才是可序列化对象。", font2);// 创建一个段落
section1.add(text);// 将段落写入小节中
text = new Paragraph("File类主要方法列表", font2);
section1.add(text);
Table table = new Table(2, 5); // 创建表格对象
table.setBorderColor(new Color(220, 255, 100)); // 设置表格边框颜色
// 设置单元格的边距间隔等
table.setPadding(1);
table.setSpacing(1);
table.setBorderWidth(1);
Cell cell = null; // 单元格对象
// 添加表头信息
cell = new Cell(new Paragraph("方法名称", font2));
cell.setHeader(true);
table.addCell(cell);
cell = new Cell(new Paragraph("用法", font2));
cell.setHeader(true);
table.addCell(cell);
table.endHeaders();
// 添加表的内容
table.addCell(new Cell("public Boolean canread()"));
table.addCell(new Cell(new Paragraph("测试这个文件是否可以读?", font2)));
table.addCell(new Cell("public Boolean canwrite()"));
table.addCell(new Cell(new Paragraph("测试这个文件是否可写?", font2)));
table.addCell(new Cell("public Boolean createNewFile()"));
table.addCell(new Cell(new Paragraph(
"看这个文件或目录是否存在,如有此文件则返回false,如果没有这个文件则创建这个类的对象.", font2)));
table.addCell(new Cell("public Boolean delete()"));
table.addCell(new Cell(new Paragraph(
"删除当前对象所指文件。删除成功返回true,否则返回false.", font2)));
section1.add(table); // 将表格对象添加到小节对象中
List list = new List(true, false, 20);// 创建列表
ListItem item = new ListItem("带缓存的字符输出流BufferedWriter类;", font2);// 创建列表项
list.add(item);// 将列表项添加到列表中
item = new ListItem("字符输入流FileReader类和FileWriter类的使用;", font2);
list.add(item);
item = new ListItem("读取带缓存的BufferedReader字符流t.", font2);
list.add(item);
section1.add(list); // 将列表对象添加到小节对象中
// 将章节对象加入到文档中
document.add(chapter1);
// 关闭文档
document.close();
System.out.println("PDF文件生成成功,PDF文件名:" + file.getAbsolutePath());
} catch (DocumentException e) {
System.out.println("PDF文件" + file.getAbsolutePath() + "生成失败!" + e);
e.printStackTrace();
} catch (IOException ee) {
System.out.println("PDF文件" + file.getAbsolutePath() + "生成失败!" + ee);
ee.printStackTrace();
} finally {
if (out != null) {
try {
// 关闭输出文件流
out.close();
} catch (IOException e1) {
}
}
}
}
public static void main(String[] args) {
StreamDemo_15 pdf = new StreamDemo_15();
String fileName = "D:/temp/myPDF.pdf";
pdf.creatPDF(fileName);
}
}
实例137 读取PDF文件中的内容
package Chapter07.stream;
import java.awt.Color;
import java.io.FileOutputStream;
import java.io.IOException;
import com.lowagie.text.Cell;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.FontFactory;
import com.lowagie.text.Image;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.Table;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.rtf.RtfWriter2;
//用iText生成word文件
public class StreamDemo_16 {
public void createDocFile(String file) throws DocumentException,
IOException {
// 设置纸张大小
Document document = new Document(PageSize.A4);
// 建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中
RtfWriter2.getInstance(document, new FileOutputStream(file));
document.open();
// 设置中文字体
BaseFont macintosh = BaseFont.createFont(
"C:\\WINDOWS\\Fonts\\STFANGSO.TTF", BaseFont.IDENTITY_H,
BaseFont.EMBEDDED);
// 标题字体风格
Font ThemeFont = new Font(macintosh, 18, Font.BOLD);
// 设置标题字体的颜色
ThemeFont.setColor(Color.RED);
// 正文字体风格
Font bodyFont = new Font(macintosh, 14, Font.NORMAL);
// 设置正文字体的颜色
bodyFont.setColor(56, 94, 15);
// 创建主题的Phrases对象
Paragraph theme = new Paragraph("主标题");
// 将设置好的字体添加到主题的短句上
theme.setAlignment(Element.ALIGN_CENTER);
theme.setFont(ThemeFont);
// 将Phrases添加到document文档中
document.add(theme);
// 设置word正文中的内容
String bodyText = "Java程序通过流来完成输入/输出,它是生产或消费信息的抽象。"
+ "流通过Java的输入/输出系统与物理设备链接,尽管与它们链接的物理设备不尽相同,"
+ "但是所有流的行为具有同样的方式,这样,相同的输入/输出类和方法适用于所有类型的外部设备,"
+ "这意味着一个输入流能够抽象多种不同类型的输入:从磁盘文件,从键盘或从网络套接字,"
+ "同样,一个输出流可以输出到控制台,磁盘文件或相连的网络。"
+ "流是处理输入/输出的一个洁净的方法,例如它不需要代码理解键盘和网络的不同。"
+ "Java中流的实现是基于java.io包定义的类层次结构的。";
// 创建正文的Phrases对象
Paragraph context = new Paragraph(bodyText);
// 正文格式左对齐
context.setAlignment(Element.ALIGN_LEFT);
// 设置正文字体的颜色
context.setFont(bodyFont);
// 离上一段落(标题)空的行数
context.setSpacingBefore(3);
// 设置第一行空的列数
context.setFirstLineIndent(20);
// // 将Phrases添加到document文档中
document.add(context);
// 利用类FontFactory结合Font和Color可以设置各种各样字体样式
Paragraph line = new Paragraph("下划线的实现", FontFactory.getFont(
FontFactory.HELVETICA_BOLDOBLIQUE, 18, Font.UNDERLINE,
new Color(0, 0, 255)));
document.add(line);
// 创建Table表格
Table table = new Table(5);// 创建该表格的列数,在本程序中设为5列
int width[] = { 25, 25, 25, 25, 25 };// 每列的单元格的宽度
table.setWidths(width);// 设置每列所占比例
table.setWidth(90); // 占页面宽度 90%,相当于html中width属性
table.setAlignment(Element.ALIGN_CENTER);// 设置该表格中的元素水平方向居中显示
table.setAlignment(Element.ALIGN_MIDDLE);// 设置该表格中的元素垂直方向纵向居中显示
table.setAutoFillEmptyCells(true); // 自动填满
table.setBorderWidth(1); // 边框宽度
table.setBorderColor(new Color(160, 32, 240)); // 边框颜色
table.setPadding(2);// 单元格内部的空白距离,相当于html中的cellpadding属性
table.setSpacing(3);// 单元格之间的间距,相当于html中的cellspacing
table.setBorder(2);// 边框的宽度
// 设置表头
Cell haderCell = new Cell("用iText创建的表格-表头");// 创建单元格
haderCell.setBackgroundColor(Color.pink);// 设置此单元格的背景色
haderCell.setHeader(true);// 设置为表头
haderCell.setColspan(5);// 合并列的列数
haderCell.setHorizontalAlignment(haderCell.ALIGN_CENTER);// 水平显示的位置
table.addCell(haderCell);// 将单元格添加到表格中
table.endHeaders();// 结束表头的设置
Font fontChinese = new Font(macintosh, 15, Font.NORMAL, Color.blue);// 设置字体风格
Cell cell = new Cell(new Phrase("这是一个3行1列合并的表格", fontChinese));// 创建单元格
cell.setVerticalAlignment(Element.ALIGN_TOP);
cell.setBorderColor(new Color(255, 215, 0));
cell.setRowspan(3);// 设置合并的行数
// 添加单元格
table.addCell(cell);
table.addCell(new Cell("第一行第一列"));
table.addCell(new Cell("第一行第二列"));
table.addCell(new Cell("第一行第三列"));
table.addCell(new Cell("第一行第四列"));
table.addCell(new Cell("第二行第一列"));
table.addCell(new Cell("第二行第二列"));
table.addCell(new Cell("第二行第三列"));
table.addCell(new Cell("第二行第四列"));
table.addCell(new Cell("第三行第一列"));
table.addCell(new Cell("第三行第二列"));
table.addCell(new Cell("第三行第三列"));
table.addCell(new Cell("第三行第四列"));
// 创建一个合并5列的单元格
Cell cell3 = new Cell(new Phrase("一行5列合并的表格", fontChinese));
cell3.setColspan(5);
cell3.setVerticalAlignment(Element.ALIGN_CENTER);
table.addCell(cell3);
document.add(table);
// 添加图片
Image img = Image.getInstance("D:\\图片\\2.jpg");
img.setAbsolutePosition(0, 0);//
img.setAlignment(Image.ALIGN_LEFT);// 设置图片显示位置
img.scaleAbsolute(120, 350);// 直接设定显示尺寸
img.scalePercent(80);// 表示显示的大小为原尺寸的80%
img.scalePercent(80, 80);// 图像高宽的显示比例
img.setRotation(30);// 图像旋转一定角度
document.add(img);
document.close();
}
public static void main(String[] args) {
StreamDemo_16 word = new StreamDemo_16();
String file = "c:/demo2.doc";
try {
word.createDocFile(file);
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
实例138 用iText生成Word文件
package Chapter07.stream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.hwpf.extractor.WordExtractor;
public class StreamDemo_17 {
/**
* @param 用POI读取word文件中的内容
*/
public static void main(String[] args) {
StreamDemo_17 s = new StreamDemo_17();
String path = "C:\\fileText.doc";
try {
s.readDocFile(path);
} catch (IOException e) {
System.out.println("读取失败:" + path + "文件不存在" + e.getMessage());
}
}
public void readDocFile(String origFileName) throws IOException {
System.out.println("C:\\fileText.doc中的内容如下:\n");
// 创建文件输入流
FileInputStream in = new FileInputStream(new File(origFileName));
WordExtractor extractor = null;
String text = null;
// 创建WordExtractor
extractor = new WordExtractor(in);
// 对DOC文件进行提取
text = extractor.getText();
System.out.println(text);
}
}
实例139 利用POI读取Word文件中的内容
package Chapter07.stream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.pdfbox.pdfparser.PDFParser;
import org.pdfbox.pdmodel.PDDocument;
import org.pdfbox.util.PDFTextStripper;
public class StreamDemo_18 {
/**
* @param 读取PDF文件
*/
public static void main(String[] args) {
StreamDemo_18 pdf = new StreamDemo_18();
String pdfName = "D:\\temp\\myPDF.pdf";
pdf.readFileOfPDF(pdfName);
}
// 读取指定的PDF文件的内容,其中:pdfName表示要读取的PDF文件的路径
public void readFileOfPDF(String pdfName) {
File file = new File(pdfName);// 创建一个文件对象
FileInputStream infile = null;
try {
infile = new FileInputStream(pdfName);// 创建一个文件输入流
// 新建一个PDF解析器对象
PDFParser parser = new PDFParser(infile);
// 对PDF文件进行解析
parser.parse();
// 获取解析后得到的PDF文档对象
PDDocument pdfdocument = parser.getPDDocument();
// 新建一个PDF文本剥离器
PDFTextStripper stripper = new PDFTextStripper();
// 从PDF文档对象中剥离文本
String context = stripper.getText(pdfdocument);
System.out.println("PDF文件" + file.getAbsolutePath() + "的文本内容如下:");
System.out.println(context);
} catch (Exception e) {
System.out.println("读取PDF文件" + file.getAbsolutePath() + "失败!"
+ e.getMessage());
} finally {
if (infile != null) {
try {
infile.close();
} catch (IOException e1) {
}
}
}
}
}