JAVA IO流基础2
集合到文件
public static void main(String[] args)throws IOException {
ArrayList<String> array = new ArrayList<>();
//往集合中存储字符元素
array.add("Hello");
array.add("World");
array.add("Java");
//创建字符缓冲输出流
BufferedWriter bw = new BufferedWriter(new FileWriter("ooo.txt"));
//遍历array集合,得到每一个字符串数据
for (String s : array) {
//用字符缓冲流对象特有方法写数据
bw.write(s);
bw.newLine();
bw.flush();
}
bw.close();
}
改进版
public static void main(String[] args) throws IOException {
//
ArrayList<IoStudent> arr = new ArrayList<IoStudent>();
IoStudent s1 = new IoStudent("id001", "光水奶", 19, "第七史诗1");
IoStudent s2 = new IoStudent("id002", "光修理", 22, "第七史诗2");
IoStudent s3 = new IoStudent("id003", "光响指", 24, "第七史诗3");
IoStudent s4 = new IoStudent("id004", "光锤", 18, "第七史诗4");
arr.add(s1);
arr.add(s2);
arr.add(s3);
arr.add(s4);
BufferedWriter bw = new BufferedWriter(new FileWriter("ooo.txt"));
for (IoStudent is : arr) {
StringBuilder sb = new StringBuilder();
sb.append(is.getId()).append(",").append(is.getName()).append(",").append(is.getAge()).append(",").append(is.getAddress());
bw.write(sb.toString());
bw.newLine();
bw.flush();
}
bw.close();
}
排序改进版+
学生类
public class IoStudent {
private String name;
private int chinese;
private int math;
private int english;
public IoStudent() {
super();
}
public IoStudent(String name, int chinese, int math, int english) {
super();
this.name = name;
this.chinese = chinese;
this.math = math;
this.english = english;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getChinese() {
return chinese;
}
public void setChinese(int chinese) {
this.chinese = chinese;
}
public int getMath() {
return math;
}
public void setMath(int math) {
this.math = math;
}
public int getEnglish() {
return english;
}
public void setEnglish(int english) {
this.english = english;
}
public int getSum() {
return this.chinese + this.math + this.english;
}
}
操作录入
public static void main(String[] args) throws IOException {
TreeSet<IoStudent> is = new TreeSet<IoStudent>(new Comparator<IoStudent>() {
@Override
public int compare(IoStudent o1, IoStudent o2) {
int num = o2.getSum() - o1.getSum();
int num2 = num == 0 ? o2.getChinese() - o1.getChinese() : num;
int num3 = num2 == 0 ? o2.getMath() - o1.getMath() : num2;
int num4 = num3 == 0 ? o2.getName().compareto(o1.getName()) : num3;
return num4;//o2在前则是倒序
}
});
for (int i = 0; i < 5; i++) {
Scanner sc = new Scanner(system.in);
System.out.println("请输入第"+(i+1)+"个学生数据");
System.out.println("姓名:");
String name = sc.nextLine();
System.out.println("语文成绩:");
int chinese = sc.nextInt();
System.out.println("数学成绩:");
int math = sc.nextInt();
System.out.println("英语成绩:");
int english = sc.nextInt();
IoStudent ios = new IoStudent(name,chinese,math,english);//有参构造
is.add(ios);
}
BufferedWriter bw = new BufferedWriter(new FileWriter("ooo.txt"));
for (IoStudent i : is) {
StringBuilder sb = new StringBuilder();
sb.append(i.getName()).append(",").append(i.getChinese()).append(",").append(i.getMath()).append(",").append(i.getEnglish());
String s = sb.toString();
bw.write(s);
bw.newLine();
bw.flush();
}
bw.close();
}
文件到集合
public static void main(String[] args) throws IOException {
//创建字符缓冲输入流
BufferedReader br = new BufferedReader(new FileReader("ooo.txt"));
//创建Array集合
ArrayList<String> array = new ArrayList<>();
//使用字符缓冲流对象特有读数据并加入进array集合
String line;
while ((line = br.readLine()) != null){
array.add(line);
}
br.close();
//遍历集合检查结果
for (String s : array) {
System.out.println(s);
}
}
改进版
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("ooo.txt"));
ArrayList<IoStudent> array = new ArrayList<IoStudent>();
String line;
while((line = br.readLine())!= null){
String[] sp = line.split(",");//以“,”为基准分割成数组
IoStudent is = new IoStudent();
is.setId(sp[0]);
is.setName(sp[1]);
is.setAge(Integer.parseInt(sp[2]));//讲string类型转换成int
is.setAddress(sp[3]);
array.add(is);
}
for (IoStudent ios : array) {
System.out.println(ios.getId()+","+ios.getName()+","+ios.getAge()+","+ios.getAddress());
}
}
点名器
public static void main(String[] args) throws IOException {
//建立字符缓冲输入流
BufferedReader br = new BufferedReader(new FileReader("ooo.txt"));
//建立Array集合
ArrayList<String> arr = new ArrayList<>();
//通过字符缓冲流的特有对象方法读数据并把字符串加进arr集合
String line;
while ((line = br.readLine()) != null) {
arr.add(line);
}
//释放资源
br.close();
//建立一个随机数范围在0到集合长度作为下标
Random r = new Random();
int index = r.nextInt(arr.size());
//将指定下标获得的名字赋值成String对象
String name = arr.get(index);
//输出对象
System.out.println("点到的人是:" + name);
}
复制单级文件夹
public static void main(String[] args) throws IOException{
//创建数据源目录对象
File y1 = new File("G:\\javva");
//获取数据源目录对象名称
String fn = y1.getName();
//创建目的地目录源ile对象
File d1 = new File(fn);
//判断目的地数据源目录是否存在,如果存在则创造目录
if(!d1.exists()){
d1.mkdir();
}
File[] ylist = y1.listFiles();
for (File filer : ylist) {
String fileName = filer.getName();
File d2 = new File(d1,fileName);
//复制文件
copyFile(filer,d2);
}
}
private static void copyFile(File filer, File d2) throws IOException {
//由于文件类型多样,使用字节缓冲流进行复制
BufferedInputStream bi = new BufferedInputStream(new FileInputStream(filer));
bufferedoutputstream bo = new bufferedoutputstream(new FileOutputStream(d2));
byte[] by = new byte[1024];
int len;
while((len=bi.read(by))!=-1){
bo.write(by,0,len);
}
bi.close();
bo.close();
}
复制多级文件
public static void main(String[] args) throws IOException{
//创建数据源file对象
File scrFile = new File("G:\\javva");
//创建目的地file对象
File destFile = new File("F:\\");
//写方法实现文件夹的复制,参数位数据源对象和目的地对象
copyFolder(scrFile,destFile);
}
private static void copyFolder(File scrFile, File destFile) throws IOException{
//判断数据源对象是否是文件夹
if(scrFile.isDirectory()){
String scrFileName = scrFile.getName();
File newFolder = new File(destFile,scrFileName);
if (!newFolder.exists()){//这里的条件判断一定要注意“!”是否写上否则会出错
newFolder.mkdir();
}
//获取数据源file下所有文件或者目录的file数组
File[] listFiles = scrFile.listFiles();
for (File listFile : listFiles) {
copyFolder(listFile,newFolder);
}
}else{//如果不是文件夹则直接调用文件字节流复制
File newFile = new File(destFile,scrFile.getName());
copyFile(scrFile,newFile);
}
}
private static void copyFile(File scrFile, File destFile) throws IOException {
//由于文件类型多样,使用字节缓冲流进行复制
BufferedInputStream bi = new BufferedInputStream(new FileInputStream(scrFile));
bufferedoutputstream bo = new bufferedoutputstream(new FileOutputStream(destFile));
byte[] by = new byte[1024];
int len;
while((len=bi.read(by))!=-1){
bo.write(by,0,len);
}
bi.close();
bo.close();
}
复制文件的异常处理
特殊操作流
标准输入输出流
- System类中有两个静态成员
public static void main(String[] args) throws IOException {
// //public static final InputStream in: 标准输入流
// InputStream is = system.in; //多态的方式返回的子类对象
//
// int by;
// while ((by = is.read()) != -1) {
// System.out.println((char) by);//读取汉字是乱码所以要用字符流
// }
//
// //如何把字节流转换为字符流?用转换流
// InputStreamReader isr = new InputStreamReader(is);
// //想要一次读一行则需要继续转换为字符缓冲输入流
// BufferedReader br = new BufferedReader(isr);
//将上面的各种定义简略成一行
BufferedReader br = new BufferedReader(new InputStreamReader(system.in));
System.out.println("请输入一行字:");
String line = br.readLine();
System.out.println("您输入的内容为:" + line);
//如果需要读取数字int类型,则需要转换
System.out.println("请输入数字:");
int i = Integer.parseInt(br.readLine());
System.out.println("你输入的数字是:" + i);
//由此可见,自己实现键盘录入数据太麻烦了,所以java提供了一个类供我们使用:scannar
Scanner sc = new Scanner(system.in);
}
标准输出流
- print()里必须要带参数
打印流
打印流分类
- 字节打印流:PrintStream
- PrintStream(String fileName):使用指定的文件名创建新的打印流
使用继承父类的方法写数据(write)查看的时候会转码,使用自己特有方法写数据(print)查看数据时原样输出
- 字符打印流:PrintWriter
PrintWriter的优点
复制java文件(打印流改进版)
public static void main(String[] args) throws IOException {
// //创建字符缓冲输入输出流
// BufferedReader br = new BufferedReader(new FileReader("G:\\javva\\jj.txt"));
// BufferedWriter bw = new BufferedWriter(new FileWriter("copy.txt"));
//
// //读写数据,复制文件
// String line;
// while ((line = br.readLine())!=null){
// bw.write(line);
// bw.newLine();
// bw.flush();
// }
// //释放资源
// bw.close();
// br.close();
//使用打印流改进
BufferedReader br = new BufferedReader(new FileReader("G:\\javva\\jj.txt"));
//读取则照用
PrintWriter pw = new PrintWriter(new FileWriter("copy.txt"));
String line;
while ((line = br.readLine())!=null){
pw.println(line);
}
//释放资源
br.close();
pw.close();
}
对象序列化流
-
对象序列化:就是将对象保存到磁盘中,或者在网络中传输对象
-
这种机制就是使用一个字节序列表示一个对象,该字节序列包含:对象的类型,对象的数据和对象的属性等信息,字节序列写到文件之后,相当于文件中持久保存了一个对象的信息,反之,该字节序列还可以从文件中读取回来,重构对象,对它进行反序列化
-
要实现序列化和反序列化就要使用对象序列化流和对象反序列化流
-
对像序列化流:ObjectOutputStream
-
将java对象的原始数据类型和图形写入ObjectOutputStream,可以使用ObjectInputStream读取(重构)对象,可以可以通过流的文件来实现对象的持久储存,如果是网络套接字流,则可以在另一个主机或另一个进程中重构对象
-
public static void main(String[] args) throws IOException { //写入序列化流 ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("oos.txt")); //创建对象 IoStudent s1 = new IoStudent("徐志远",100,100,100); //注意,对象的类需要实现Serializable接口,这个接口不需要重写,是一个标识接口 //将对象写入序列化 oos.writeObject(s1);//写入后的文件是一堆乱码,需要反序列化流读取 //释放资源 oos.close(); }
-
-
对像反序列化流:ObjectInputStream
-
public static void main(String[] args) throws IOException, ClassNotFoundException {
//建立反序列对象
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("oos.txt"));
//反序列化读取对象
Object obj = ois.readobject();
//将对象转化为IoStudent类的对象
IoStudent s1 = (IoStudent)obj;
System.out.println(s1.getName()+","+s1.getChinese()+","+s1.getMath()+","+s1.getEnglish()+","+s1.getSum());
//释放资源
ois.close();
}
serialVesionUID&transient
-
会出问题,因为修改了类文件就会改变他的序列化id:serialVesionUID,再次读取的时候与本地的序列化id不一致则会出现错误InvaildClassException
- 当序列化运行时检测到类中的以下问题之一时抛出
- 类的串行版本与流中读取的类型述符的类型不匹配(也就是上面所说的序列化id不一致
- 该类包含未知的数据类型
- 该类没有可访问的无参数构造函数
- 当序列化运行时检测到类中的以下问题之一时抛出
-
如何解决?
-
如果不想被序列化如何实现
Properties作为Map集合的使用与特有方法
- Properties概述
- 是一个Map体系的集合类
- Properties可以保存到流中或者从流中加载
public static void main(String[] args) {
//创建集合对象
Properties prop = new Properties();//没有泛型
//储存元素
prop.put("id001","xu");
prop.put("id002","zhi");
prop.put("id003","yuan");
//遍历集合
Set<Object> keySet = prop.keySet();//没有泛型指定所以默认时object
for (Object key : keySet) {
Object value = prop.get(key);
System.out.println(key+","+value);
}
}
- Properties作为集合的特有方法
public static void main(String[] args) {
//创建集合对象
Properties prop = new Properties();//没有泛型
//储存元素
prop.setProperty("id001", "xu");
prop.setProperty("id002", "zhi");
prop.setProperty("id003", "yuan");//setProperty通过对put方法的代码的改写能够接受String类型而不是put只能接收Object类型
//搜索
// System.out.println(prop.getProperty("id001"));//根据键获取值
//遍历集合
// System.out.println(prop);
Set<String> names = prop.stringPropertyNames();
for (String keys : names) {
// System.out.println(keys);
String values = prop.getProperty(keys);
System.out.println(keys + "," + values);
}
}
-
Properties和IO流相结合的特有方法
public static void main(String[] args) throws IOException{
//把集合中的数据保存到文件
myStore();
//把文件中的数据加载到集合
myload();
}
private static void myload() throws IOException{
Properties prop = new Properties();
FileReader fr = new FileReader("output.txt");
prop.load(fr);
fr.close();
System.out.println(prop);
}
private static void myStore() throws IOException {
Properties prop = new Properties();
prop.setProperty("id001","xuzhiyuan");
prop.setProperty("id002","ximu");
prop.setProperty("id003","tianming");
FileWriter fw = new FileWriter("output.txt");
prop.store(fw,null);
fw.close();
}
实例:游戏次数
-
首先是游戏类
public class Game { private Game(){ } public static void start(){ Random r = new Random(); int i = r.nextInt(100)+1; while(true){ Scanner sc = new Scanner(system.in); System.out.println("请输入你要猜的数字:"); int guessNumber = sc.nextInt(); if(guessNumber > i){ System.out.println("你猜的数字"+guessNumber+"......大了"); }else if(guessNumber < i){ System.out.println("你猜的数字"+guessNumber+"......小了"); }else{ System.out.println("恭喜你猜对了!"); break; } } } }
-
随后是执行判断类
public static void main(String[] args) throws IOException { //从文件中读取数据到Properties集合,使用load实现 Properties prop = new Properties(); FileReader fr = new FileReader("game.txt"); prop.load(fr); fr.close(); //通过集合获取游戏玩的次数 String count = prop.getProperty("count"); int number = Integer.parseInt(count); //判断游玩次数是否达到3次 if(number > 3){ System.out.println("游戏试玩已经结束,想继续游玩请充值"); }else{ Game.start(); //次数+1 number++; //通过集合写入键值,int类型的number转换成string类型 prop.setProperty("count",String.valueOf(number)); //再使用输出流将数据输出到文件 FileWriter fw = new FileWriter("game.txt"); prop.store(fw,null); fw.close(); } }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。