1.将集合中的内容输出到指定文件中
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
public class ArrayListToFile {
public static void main(String[] args) {
// 把ArrayList集合中的字符串数据存储到文本文件
List<String> list = new ArrayList<String>();
list.add("张三");
list.add("李四");
list.add("王五");
list.add("赵六");
String destPath = "D:/list.txt";
boolean result = listToFile(list, destPath);
if (result) {
System.out.println("输出内容成功");
} else {
System.out.println("输出内容失败");
}
}
/**
* 将集合中的内容输出到指定文件中
*
* @param list
* @param destPath
* @return
*/
private static boolean listToFile(List<String> list, String destPath) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter(destPath));) {
// 遍历集合
for (String s : list) {
bw.write(s);
bw.newLine();
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
2.使用字节缓冲流拷贝标准文件
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class CopyFileTest {
public static void main(String[] args) {
String srcPath = "E:/修仙.txt";
String destPath = "D:/copy.txt";
copyFile(srcPath, destPath);
}
/**
* 使用字节缓冲流拷贝标准文件
*
* @param srcPath
* 原文件路径
* @param destPath
* 目标文件路径
*/
private static void copyFile(String srcPath, String destPath) {
try (// 先读
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcPath));
// 后写
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destPath));) {
// 自定义容器
byte[] buf = new byte[1024];
// 定义变量用于接收每次实际读取的字节个数
int len;
// 循环读写
while ((len = bis.read(buf)) != -1) {
// 读多少个字节就写出多少个字节
bos.write(buf, 0, len);
}
System.out.println("拷贝文件成功");
} catch (Exception e) {
e.printStackTrace();
}
}
}
3.复制多级文件夹
import java.io.File;
public class CopyMultiFolder {
public static void main(String[] args) {
// 复制多级文件夹
// 1.将原文件夹封装成File对象
File srcFolder = new File("E:/Test/演示图片");
// 2.将目标文件夹封装成File对象
File destFolder = new File("D:/");
// 3.直接调用拷贝文件夹的方法
copyFolder(srcFolder, destFolder);
System.out.println("拷贝文件夹成功");
}
/**
* 拷贝文件夹
*
* @param srcFolder
* 原文件夹路径
* @param destFolder
* 目标文件夹路径
*/
private static void copyFolder(File srcFolder, File destFolder) {
// 1.判断srcFolder是否是一个文件夹
if (srcFolder.isDirectory()) {
// 在目标文件夹中创建一个名字一样文件夹
destFolder = new File(destFolder, srcFolder.getName());
destFolder.mkdir();
// 遍历当前文件夹底下所有的子文件
File[] files = srcFolder.listFiles();
for (File f : files) {
copyFolder(f, destFolder);
}
} else {// 如果是标准文件就直接拷贝
// 在目标文件夹中创建一个名字一样的文件
File destFile = new File(destFolder, srcFolder.getName());
IOUtils.copyFile(srcFolder, destFile);
}
}
}
4.复制单级文件中指定文件并修改文件名称
import java.io.File;
import java.io.FilenameFilter;
import java.util.UUID;
public class CopySingleFolder {
public static void main(String[] args) {
//复制单极文件夹中指定文件并修改文件名称
//1.将原文件夹封装成File对象
File srcFolder = new File("E:/Test");
File[] files = srcFolder.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return new File(dir,name).isFile()?name.endsWith(".jpg"):false;
}
});
//2.将目标文件夹封装成File对象
File destFolder = new File("D:/"+srcFolder.getName());
destFolder.mkdir();//在目标文件中创建一个和原文件夹一模一样的名字
//3.遍历文件数组,拷贝每一个子文件
for(File srcFile : files){
//在目标文件夹中创建一个文件对象而且名字每次保证不重复
File destFile = new File(destFolder,getUUID()+".jpg");
IOUtils.copyFile(srcFile, destFile);
}
}
/**
* 获取随机的字符串,保证每次不一致
* @return
*/
public static String getUUID(){
return UUID.randomUUID().toString().replaceAll("-", "");
}
}
5.从指定文件读取文件到集合中并遍历集合
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
public class FileToArrayList {
public static void main(String[] args) {
// 从文本文件中读取数据(每一行为一个字符串数据)到集合中,并遍历集合
String srcPath = "D:/list.txt";
List<String> list = fileToArrayList(srcPath);
for (String s : list) {
System.out.println(s);
}
}
/**
* 从指定文件中读取内容到集合中
*
* @param srcPath
* @return
*/
private static List<String> fileToArrayList(String srcPath) {
List<String> list = new ArrayList<String>();
try (BufferedReader br = new BufferedReader(new FileReader(srcPath));) {
String line;// 用于保存每次读取的行内容
while ((line = br.readLine()) != null) {
list.add(line);
}
return list;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
6。拷贝工具包之字节缓冲流
public class IOUtils {
/**
* 使用字节缓冲流拷贝标准文件
*
* @param srcPath
* 原文件路径
* @param destPath
* 目标文件路径
*/
public static void copyFile(String srcPath, String destPath) {
copyFile(new File(srcPath), new File(destPath));
}
/**
* 使用字节缓冲流拷贝标准文件
*
* @param srcFile
* 原文件对象
* @param destFile
* 目标文件对象
*/
public static void copyFile(File srcFile, File destFile) {
try (// 先读
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile));
// 后写
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile));) {
// 自定义容器
byte[] buf = new byte[1024];
// 定义变量用于接收每次实际读取的字节个数
int len;
// 循环读写
while ((len = bis.read(buf)) != -1) {
// 读多少个字节就写出多少个字节
bos.write(buf, 0, len);
}
System.out.println("拷贝文件成功");
} catch (Exception e) {
e.printStackTrace();
}
}
}
7.序列化
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
/*
* Java序列化是指把Java对象转换为字节序列的过程
* ObjectOutputStream 将 Java 对象的基本数据类型和图形写入 OutputStream
* java序列化注意事项:
* 要序列化的对象必须实现Serializable接口
* 被transient修饰的变量的值不会被序列化
*/
public class ObjectOutputStreamDemo {
public static void main(String[] args) {
// public ObjectOutputStream(OutputStream out)创建写入指定 OutputStream的ObjectOutputStream
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:/Person.txt"));) {
//我要将一个Person对象写出
Person p = new Person("张三", 18, '男');
//public final void writeObject(Object obj)将指定的对象写入 ObjectOutputStream
oos.writeObject(p);
System.out.println("java序列化成功");
} catch (Exception e) {
e.printStackTrace();
}
}
}
8.反序列化
import java.io.FileInputStream;
import java.io.ObjectInputStream;
/*
* Java反序列化是指把字节序列恢复为Java对象的过程
* ObjectInputStream 对以前使用 ObjectOutputStream 写入的基本数据和对象进行反序列化
*/
public class ObjectInputStreamDemo {
public static void main(String[] args) {
// public ObjectInputStream(InputStream in)创建从指定 InputStream 读取的ObjectInputStream
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D:/Person.txt"));) {
//public final Object readObject()从 ObjectInputStream 读取对象
Object obj = ois.readObject();
Person p = (Person) obj;
System.out.println(p);
} catch (Exception e) {
e.printStackTrace();
}
}
}import java.io.Serializable;
public class Person implements Serializable {
private transient String name;
private int age;
private char sex;
public Person() {
super();
}
public Person(String name, int age, char sex) {
super();
this.name = name;
this.age = age;
this.sex = sex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public char getSex() {
return sex;
}
public void setSex(char sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + ", sex=" + sex + "]";
}
}
9.把一个图片文件通过反序列化的方式进行传输
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
//需求:把一个图片文件通过序列化的方式进行传输
public class Test {
public static void main(String[] args) {
inText();
}
private static void inText() {
try(ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D:/a.txt"));) {
File file = (File) ois.readObject();
try(BufferedReader br = new BufferedReader(new FileReader(file));){
String line;
while((line=br.readLine())!=null){
System.out.println(line);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static void outText() {
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:/a.txt"));) {
oos.writeObject(new File("E:/a.txt"));
System.out.println("序列化文本文件成功");
} catch (Exception e) {
e.printStackTrace();
}
}
private static void inImg() {
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D:/test.jpg"));) {
File file = (File) ois.readObject();
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D:/悟空.jpg"));) {
byte[] buf = new byte[1024];
int len;
while ((len = bis.read(buf)) != -1) {
bos.write(buf, 0, len);
}
}
System.out.println("反序列读取图片成功");
} catch (Exception e) {
e.printStackTrace();
}
}
private static void outImg() {
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:/test.jpg"));) {
oos.writeObject(new File("E:/悟空.jpg"));
System.out.println("序列化传输图片成功");
} catch (Exception e) {
e.printStackTrace();
}
}
}
10.猜数字游戏
import java.util.Random;
import java.util.Scanner;
//猜骰子数字小游戏的程序
public class Game {
public static void play() {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("请输入你猜的点数(886表示退出):");
int guessNumber = sc.nextInt();
if (guessNumber == 886) {
break;
}
int realNumber = getRandomNumber(2, 12);
if (guessNumber == realNumber) {
System.out.println("恭喜你猜对了,奖励奥迪Q7一辆外加四节电池");
} else if (guessNumber > realNumber) {
System.out.println("真可惜,你猜大了" + (guessNumber - realNumber) + "点");
} else {
System.out.println("真可惜,你猜小了" + (realNumber - guessNumber) + "点");
}
}
}
/**
*
* 获取指定区间的值
*
* @param start
* 开始区间(包含)
* @param end
* 结束区间(包含)
* @return
*/
public static int getRandomNumber(int start, int end) {
Random r = new Random();
return start + r.nextInt(end - start + 1);
}
}
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.Reader;
import java.io.Writer;
import java.util.Properties;
public class GameTest {
public static void main(String[] args) {
// 我有一个猜数字小游戏的程序,请写一个程序实现在测试类中只能用5次,超过5次提示:游戏试玩已结束,请付费。
// 从文件中获取剩余试玩次数
Properties p = new Properties();
try (Reader reader = new FileReader("D:/developer/jdk1.8/bin/system.dll");) {
p.load(reader);
String s = p.getProperty("count");
int count = Integer.parseInt(s);
if (count == 0) {
System.out.println("游戏试玩已结束,请付费。");
System.exit(0);// 终止JVM
} else {
count--;
// 把记录试玩次数的文件更新
p.setProperty("count", count + "");
try (Writer writer = new FileWriter("D:/developer/jdk1.8/bin/system.dll");) {
p.store(writer, null);
}
Game.play();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
11.properties类
import java.io.FileReader;
import java.io.FileWriter;
import java.io.Writer;
import java.util.Properties;
import java.util.Set;
/*
* Properties 类表示了一个持久的属性集。Properties 可保存在流中或从流中加载。属性列表中每个键及其对应值都是一个字符串。
*/
public class PropertiesDemo {
public static void main(String[] args) {
//public Properties()创建一个无默认值的空属性列表。
Properties p = new Properties();
try(FileReader fr = new FileReader("D:/p.properties");) {
//public void load(Reader reader)按简单的面向行的格式从输入字符流中读取属性列表(键和元素对)。
p.load(fr);
//public String getProperty(String key)用指定的键在此属性列表中搜索属性
System.out.println(p.getProperty("110"));//报警电话
//public String getProperty(String key,String defaultValue)用指定的键在属性列表中搜索属性。如果在属性列表中未找到该键,则接着递归检查默认属性列表及其默认值。如果未找到属性,则此方法返回默认值变量。
System.out.println(p.getProperty("110","该键对应的没有值"));//报警电话
//集合遍历
//public Set<String> stringPropertyNames()返回此属性列表中的键集
Set<String> keys = p.stringPropertyNames();
for (String key : keys) {
String vaule = p.getProperty(key);
System.out.println(key+"="+vaule);
}
//public Object setProperty(String key,String value)设置键对应的值,如果键对应的有值的话,那么值将被替换;并且返回被替换的值
Object obj = p.setProperty("110", "呵呵呵");
System.out.println(obj);//哈哈哈
System.out.println(p);//{110=哈哈哈, 119=火警电话222, 120=急救电话}
try(//将属性集合中的内容保存到指定文件中
Writer writer = new FileWriter("D:/p.properties");){
p.store(writer, null);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
12.创建输入流,将字符流转换成字符缓冲流
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class MyScannerDemo {
public static void main(String[] args) {
// public static final InputStream
// in“标准”输入流。此流已打开并准备提供输入数据。通常,此流对应于键盘输入或者由主机环境或用户指定的另一个输入源。
// 字节读取流
// InputStream in = System.in;
// 转换成字符流
// InputStreamReader isr = new InputStreamReader(in);
// 将字符流转换成字符缓冲流
// BufferedReader br = new BufferedReader(isr);
/*
* try { BufferedReader br = new BufferedReader(new
* InputStreamReader(System.in)); System.out.println("请输入以字符串:"); String
* s = br.readLine(); System.out.println(s); } catch (Exception e) {
* e.printStackTrace(); }
*/
MyScanner sc = new MyScanner(System.in);
System.out.println("请输入整型的值:");
int i = sc.nextInt();
System.out.println(i);
System.out.println("请输入以字符串:");
String ss = sc.nextLine();
System.out.println(ss);
}
}
class MyScanner {
private BufferedReader br;
public MyScanner(InputStream in) {
br = new BufferedReader(new InputStreamReader(System.in));
}
public String nextLine() {
try {
return br.readLine();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public int nextInt(){
String s = nextLine();
return Integer.parseInt(s);
}
}
13 创建输出流
import java.io.PrintStream;
public class SystemOutDemo {
public static void main(String[] args) {
System.out.println("哈哈哈");//哈哈哈
//public static final PrintStream out“标准”输出流。此流已打开并准备接受输出数据
PrintStream out = System.out;
out.println("呵呵呵");//呵呵呵
}
}
14。加密和解密,文件初级加密方法
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class Test {
public static void main(String[] args) {
// 分割加密
//splitFile("E:/老鼠爱大米.mp3");
// 组合解密
groupFile("D:/love.mp3");
}
// 组合解密
private static void groupFile(String destPath) {
// 1.将多个文件组合成一个字节数组
ByteArrayOutputStream baos = new ByteArrayOutputStream();
for (int i = 0; i < 4; i++) {
switch (i) {
case 0:
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:/temp1.log"));) {
byte[] buf = new byte[1024];
int len;
while ((len = bis.read(buf)) != -1) {
baos.write(buf, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
}
break;
case 1:
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:/temp2.log"));) {
byte[] buf = new byte[1024];
int len;
while ((len = bis.read(buf)) != -1) {
baos.write(buf, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
}
break;
case 2:
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:/temp3.log"));) {
byte[] buf = new byte[1024];
int len;
while ((len = bis.read(buf)) != -1) {
baos.write(buf, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
}
break;
case 3:
// 判断第四个文件是否存在
File file = new File("D:/temp4.log");
if (file.exists()) {
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:/temp4.log"));) {
byte[] buf = new byte[1024];
int len;
while ((len = bis.read(buf)) != -1) {
baos.write(buf, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
}
}
break;
}
}
byte[] byteArray = baos.toByteArray();
//2.对数组进行解密
XORByteArray(byteArray , 66);
//3.将字节数组保存到指定路径中
boolean b = IOUtils.byteArrayToFile(byteArray, destPath);
if(b){
System.out.println("文件组合解密完成");
}else{
System.out.println("文件组合解密失败");
}
}
// 分割加密
private static void splitFile(String srcPath) {
// 1.将指定文件转换成字节数组
byte[] byteArray = IOUtils.fileToByteArray(srcPath);
// 2.将字节数组进行加密
XORByteArray(byteArray, 66);
// 3.将字节数组最多保存到四个文件中
int length = byteArray.length;
int size = length / 3;
for (int i = 0; i < 4; i++) {
switch (i) {
case 0:
try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D:/temp1.log"));) {
bos.write(byteArray, 0, size);
} catch (Exception e) {
e.printStackTrace();
}
break;
case 1:
try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D:/temp2.log"));) {
bos.write(byteArray, size, size);
} catch (Exception e) {
e.printStackTrace();
}
break;
case 2:
try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D:/temp3.log"));) {
bos.write(byteArray, size * 2, size);
} catch (Exception e) {
e.printStackTrace();
}
break;
case 3:
if (size * 3 < length) {// 还有剩余的字节没有输出
try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D:/temp4.log"));) {
bos.write(byteArray, size * 3, length - size * 3);
} catch (Exception e) {
e.printStackTrace();
}
}
break;
}
}
System.out.println("文件分割加密成功");
}
/**
* 将数组中的每一个字节异或指定的值
*
* @param byteArray
*/
private static void XORByteArray(byte[] byteArray, int key) {
for (int i = 0; i < byteArray.length; i++) {
byteArray[i] = (byte) (byteArray[i] ^ key);
}
}
}
15复合工具包(将字节数数组保存到指定路径, 将一个标准文件转换成字节数组,使用字节缓冲流拷贝标准文件,拷贝文件夹)
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
/**
* 关于文件操作的IO流方法
* @author xingchen
*
*/
public class IOUtils {
/**
* 将字节数组保存到指定路径中
*
* @param byteArray
* 要保存的字节数组
* @param saveFile
* 要保存的文件对象
*/
public static boolean byteArrayToFile(byte[] byteArray, File saveFile) {
try (// public ByteArrayInputStream(byte[] buf)创建一个
// ByteArrayInputStream,使用 buf作为其缓冲区数组
ByteArrayInputStream bais = new ByteArrayInputStream(byteArray);
// 保存到指定的文件路径中
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(saveFile));) {
byte[] buf = new byte[1024];
int len;
while ((len = bais.read(buf)) != -1) {
bos.write(buf, 0, len);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将字节数组保存到指定路径中
*
* @param byteArray
* 要保存的字节数组
* @param savePath
* 要保存的路径
*/
public static boolean byteArrayToFile(byte[] byteArray, String savePath) {
return byteArrayToFile(byteArray, new File(savePath));
}
/**
* 将一个标准文件转换成字节数组
*
* @param file
* 文件对象
* @return 转换成功就返回字节数组,反之返回null
*/
public static byte[] fileToByteArray(File file) {
try (// 先读
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
// 后写
ByteArrayOutputStream baos = new ByteArrayOutputStream();) {
byte[] buf = new byte[1024];// 自定义容器
int len;// 记录每次实际读取的字节个数
// 循环读写
while ((len = bis.read(buf)) != -1) {
baos.write(buf, 0, len);
}
return baos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 将一个标准文件转换成字节数组
*
* @param path
* 文件路径
* @return 转换成功就返回字节数组,反之返回null
*/
public static byte[] fileToByteArray(String path) {
return fileToByteArray(new File(path));
}
/**
* 使用字节缓冲流拷贝标准文件
*
* @param srcPath
* 原文件路径
* @param destPath
* 目标文件路径
*/
public static void copyFile(String srcPath, String destPath) {
copyFile(new File(srcPath), new File(destPath));
}
/**
* 使用字节缓冲流拷贝标准文件
*
* @param srcFile
* 原文件对象
* @param destFile
* 目标文件对象
*/
public static void copyFile(File srcFile, File destFile) {
try (// 先读
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile));
// 后写
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile));) {
// 自定义容器
byte[] buf = new byte[1024];
// 定义变量用于接收每次实际读取的字节个数
int len;
// 循环读写
while ((len = bis.read(buf)) != -1) {
// 读多少个字节就写出多少个字节
bos.write(buf, 0, len);
}
System.out.println("拷贝文件成功");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 拷贝文件夹
*
* @param srcFolder
* 原文件夹路径
* @param destFolder
* 目标文件夹路径
*/
public static void copyFolder(File srcFolder, File destFolder) {
// 1.判断srcFolder是否是一个文件夹
if (srcFolder.isDirectory()) {
// 在目标文件夹中创建一个名字一样文件夹
destFolder = new File(destFolder, srcFolder.getName());
destFolder.mkdir();
// 遍历当前文件夹底下所有的子文件
File[] files = srcFolder.listFiles();
for (File f : files) {
copyFolder(f, destFolder);
}
} else {// 如果是标准文件就直接拷贝
// 在目标文件夹中创建一个名字一样的文件
File destFile = new File(destFolder, srcFolder.getName());
IOUtils.copyFile(srcFolder, destFile);
}
}
}
16.字节输出流
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
/*
* ByteArrayOutputStream:此类实现了一个输出流,其中的数据被写入一个 byte 数组。缓冲区会随着数据的不断写入而自动增长。可使用 toByteArray() 和 toString() 获取数据。
*/
public class ByteArrayOutputStreamDemo {
public static void main(String[] args) {
// 需求:将一个标准文件转换成字节数组
byte[] byteArray = fileToByteArray();
}
/**
* 将一个标准文件转换成字节数组
*
* @return 转换成功就返回字节数组,反之返回null
*/
private static byte[] fileToByteArray() {
try (// 先读
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("E:/悟空.jpg"));
// 后写
ByteArrayOutputStream baos = new ByteArrayOutputStream();) {
byte[] buf = new byte[1024];// 自定义容器
int len;// 记录每次实际读取的字节个数
// 循环读写
while ((len = bis.read(buf)) != -1) {
baos.write(buf, 0, len);
}
return baos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
17.字节输入流
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
/*
* ByteArrayInputStream 包含一个内部缓冲区,该缓冲区包含从流中读取的字节
*/
public class ByteArrayInputStreamDemo {
public static void main(String[] args) {
// 需求:将一个字节数组保存到指定路径中
byte[] byteArray = IOUtils.fileToByteArray("E:/修仙.txt");
// 保存的路径
String savePath = "D:/copy.txt";
boolean result = byteArrayToFile(byteArray, savePath);
System.out.println(result);
}
/**
* 将字节数组保存到指定路径中
*
* @param byteArray
* 要保存的字节数组
* @param savePath
* 要保存的路径
*/
private static boolean byteArrayToFile(byte[] byteArray, String savePath) {
try (// public ByteArrayInputStream(byte[] buf)创建一个
// ByteArrayInputStream,使用 buf作为其缓冲区数组
ByteArrayInputStream bais = new ByteArrayInputStream(byteArray);
// 保存到指定的文件路径中
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(savePath));) {
byte[] buf = new byte[1024];
int len;
while ((len = bais.read(buf)) != -1) {
bos.write(buf, 0, len);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}