当前位置: 代码迷 >> 综合 >> java基础复习-IO附加
  详细解决方案

java基础复习-IO附加

热度:46   发布时间:2023-09-23 11:43:10.0
   数据输入流:DataInputStream* 			DataInputStream(InputStream in)* 数据输出流:DataOutputStream* 			DataOutputStream(OutputStream out) 
------------------------------------------------------------------- DataInputStream dis = new DataInputStream(new FileInputStream("dos.txt"));// 读数据byte b = dis.readByte();short s = dis.readShort();int i = dis.readInt();long l = dis.readLong();float f = dis.readFloat();double d = dis.readDouble();char c = dis.readChar();boolean bb = dis.readBoolean();// 释放资源dis.close();System.out.println(b);System.out.println(s);System.out.println(i);System.out.println(l);System.out.println(f);System.out.println(d);System.out.println(c);System.out.println(bb);
----------------------------------------------private static void write() throws IOException {// DataOutputStream(OutputStream out)// 创建数据输出流对象DataOutputStream dos = new DataOutputStream(new FileOutputStream("dos.txt"));// 写数据了dos.writeByte(10);dos.writeShort(100);dos.writeInt(1000);dos.writeLong(10000);dos.writeFloat(12.34F);dos.writeDouble(12.56);dos.writeChar('a');dos.writeBoolean(true);// 释放资源dos.close();
-----------------------------------------------------------------------------------------------------------缓冲区    * 内存操作流:用于处理临时存储信息的,程序结束,数据就从内存中消失。字节数组:* 		ByteArrayInputStream* 		ByteArrayOutputStream* 字符数组:* 		CharArrayReader* 		CharArrayWriter* 字符串:* 		StringReader* 		StringWriter--------------------------字节暂存  -----同理字符串和字节数组// 写数据// ByteArrayOutputStream()ByteArrayOutputStream baos = new ByteArrayOutputStream();// 写数据for (int x = 0; x < 10; x++) {baos.write(("hello" + x).getBytes());}// public byte[] toByteArray()byte[] bys = baos.toByteArray();// 读数据// ByteArrayInputStream(byte[] buf)ByteArrayInputStream bais = new ByteArrayInputStream(bys);int by = 0;while ((by = bais.read()) != -1) {System.out.print((char) by);}--------------打印流* 字节流打印流	PrintStream* 字符打印流	PrintWriter打印流的特点:* 		A:只有写数据的,没有读取数据。只能操作目的地,不能操作数据源。* 		B:可以操作任意类型的数据。* 		C:如果启动了自动刷新,能够自动刷新。* 		D:该流是可以直接操作文本文件的。-------自动刷新    用以替代复制文件的写入办法,一句顶三句PrintWriter pw = new PrintWriter(new FileWriter("pw2.txt"),true)pw.println(任意类型)pw.close----------------- 随机访问流
模式有四种,我们最常用的一种叫"rw",这种方式表示我既可以写数据,也可以读取数据RandomAccessFile raf = new RandomAccessFile("raf.txt", "rw")raf.writeInt(100);raf.writeChar('a');raf.writeUTF("中国");raf.close();private static void read() throws IOException {// 创建随机访问流对象RandomAccessFile raf = new RandomAccessFile("raf.txt", "rw");int i = raf.readInt();System.out.println(i);// 该文件指针可以通过 getFilePointer方法读取,并通过 seek 方法设置。System.out.println("当前文件的指针位置是:" + raf.getFilePointer());char ch = raf.readChar();System.out.println(ch);System.out.println("当前文件的指针位置是:" + raf.getFilePointer());String s = raf.readUTF();System.out.println(s);System.out.println("当前文件的指针位置是:" + raf.getFilePointer());// 我不想重头开始了,我就要读取a,怎么办呢?raf.seek(4);ch = raf.readChar();System.out.println(ch);}---------------------多个文件合并   SequenceInputStreamVector<InputStream> v = new Vector<InputStream>();InputStream s1 = new FileInputStream("ByteArrayStreamDemo.java");InputStream s2 = new FileInputStream("CopyFileDemo.java");InputStream s3 = new FileInputStream("DataStreamDemo.java");v.add(s1);v.add(s2);v.add(s3);Enumeration<InputStream> en = v.elements();SequenceInputStream sis = new SequenceInputStream(en);BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("Copy.java"));// 如何写读写呢,其实很简单,你就按照以前怎么读写,现在还是怎么读写byte[] bys = new byte[1024];int len = 0;while ((len = sis.read(bys)) != -1) {bos.write(bys, 0, len);}bos.close();sis.close();}--------------------把类写进文本  序列化和反序列化  ObjectInputStream创建一个类。例如学生类,1.写完后点击黄色警告线,添加ID。以免反复读的时候出错。2.添加接口  在类后加 implements Serializable标记,不需要重写方法3.如果有不想被序列化的成员变量,在类中加关键词 transient ,例: private transient int age那么在读写的时候,age成员变量将会一直显示为0此处不做说明。。然后public class ObjectStreamDemo {public static void main(String[] args) throws IOException,ClassNotFoundException {// 由于我们要对对象进行序列化,所以我们先自定义一个类// 序列化数据其实就是把对象写到文本文件write();read();}private static void read() throws IOException, ClassNotFoundException { //抛出两个异常// 创建反序列化对象ObjectInputStream ois = new ObjectInputStream(new FileInputStream("oos.txt"));// 还原对象Object obj = ois.readObject();// 释放资源ois.close();// 输出对象System.out.println(obj);}private static void write() throws IOException {// 创建序列化流对象ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("oos.txt"));// 创建对象Person p = new Person("林青霞", 27);// public final void writeObject(Object obj)oos.writeObject(p);// 释放资源oos.close();}
}
 -------------------------------------异常处理
-------------------tryA:一个异常* B:二个异常的处理* 		a:每一个写一个try...catch* 		b:写一个try,多个catch* 			try{* 				...* 			}catch(异常类名 变量名) {* 				...* 			}* 			catch(异常类名 变量名) {* 				...* 			}* 			...* * 		注意事项:* 		1:能明确的尽量明确,不要用大的来处理。* 		2:平级关系的异常谁前谁后无所谓,如果出现了子父关系,父必须在后面。注意:* 	一旦try里面出了问题,就会在这里把问题给抛出去,然后和catch里面的问题进行匹配,* 		一旦有匹配的,就执行catch里面的处理,然后结束了try...catch* 		继续执行后面的语句。*/
--------------异常中要了解的几个方法:* public String getMessage():异常的消息字符串		* public String toString():返回异常的简单信息描述* 		此对象的类的 name(全路径名)* 		": "(冒号和一个空格) * 		调用此对象 getLocalizedMessage()方法的结果 (默认返回的是getMessage()的内容)* printStackTrace() 获取异常类名和异常信息,以及异常出现在程序中的位置。返回值void。把信息输出在控制台。
---------------------------------------throws格式:* 		throws 异常类名* 		注意:这个格式必须跟在方法的括号后面。* * 注意:* 		尽量不要在main方法上抛出异常。* 		但是我讲课为了方便我就这样做了。* * 小结:* 		编译期异常抛出,将来调用者必须处理。* 		运行期异常抛出,将来调用可以不用处理。--------------------------------------------------------------------------------* throws和throw的区别(面试题)throws用在方法声明后面,跟的是异常类名可以跟多个异常类名,用逗号隔开表示抛出异常,由该方法的调用者来处理throws表示出现异常的一种可能性,并不一定会发生这些异常throw用在方法体内,跟的是异常对象名只能抛出一个异常对象名表示抛出异常,由方法体内的语句处理throw则是抛出了异常,执行throw则一定抛出了某种异常*/
public class ExceptionDemo {public static void main(String[] args) {// method();try {method2();} catch (Exception e) {e.printStackTrace();}}public static void method() {int a = 10;int b = 0;if (b == 0) {throw new ArithmeticException();} else {System.out.println(a / b);}}public static void method2() throws Exception {int a = 10;int b = 0;if (b == 0) {throw new Exception();} else {System.out.println(a / b);}}
}
----------------------throws和try的区别后续程序需要继续运行用try,不需要继续运行用throws---------------------------------------------------finally
面试题:* 1:final,finally和finalize的区别* final:最终的意思,可以修饰类,成员变量,成员方法* 		修饰类,类不能被继承* 		修饰变量,变量是常量* 		修饰方法,方法不能被重写* finally:是异常处理的一部分,用于释放资源。* 		一般来说,代码肯定会执行,特殊情况:在执行到finally之前jvm退出了* finalize:是Object类的一个方法,用于垃圾回收
public class FinallyDemo2 {public static void main(String[] args) {System.out.println(getInt());}public static int getInt() {int a = 10;try {System.out.println(a / 0);a = 20;} catch (ArithmeticException e) {a = 30;return a;/** return a在程序执行到这一步的时候,这里不是return a而是return 30;这个返回路径就形成了。* 但是呢,它发现后面还有finally,所以继续执行finally的内容,a=40* 再次回到以前的返回路径,继续走return 30;*/} finally {a = 40;return a;//如果这样结果就是40了。}// return a;}-----------------------------------------------------------------File*创建功能:  如果忘记路径,则在项目路径下*public boolean createNewFile():创建文件 如果存在这样的文件,就不创建了*public boolean mkdir():创建文件夹 如果存在这样的文件夹,就不创建了*public boolean mkdirs():创建文件夹,如果父文件夹不存在,会帮你创建出来使用:        File file = new File("e:\\demo");System.out.println("mkdir:" + file.mkdir());* 删除功能:   File file = new File("e:\\demo");System.out.println("mkdir:" + file.delete());(不走回收站,要删除父文件夹,必先删除子的所有)重命名功能:public boolean renameTo(File dest)* 		如果路径名相同,就是改名。* 		如果路径名不同,就是改名并剪切。// File file = new File("林青霞.jpg");// File newFile = new File("东方不败.jpg");// System.out.println("renameTo:" + file.renameTo(newFile));File file2 = new File("东方不败.jpg");File newFile2 = new File("e:\\林青霞.jpg");System.out.println("renameTo:" + file2.renameTo(newFile2));* 判断功能:* public boolean isDirectory():判断是否是目录* public boolean isFile():判断是否是文件* public boolean exists():判断是否存在* public boolean canRead():判断是否可读* public boolean canWrite():判断是否可写* public boolean isHidden():判断是否隐藏* 获取功能:* public String getAbsolutePath():获取绝对路径* public String getPath():获取相对路径* public String getName():获取名称* public long length():获取长度。字节数* public long lastModified():获取最后一次的修改时间,毫秒值
----------------把毫秒值换算时间Date d = new Date(1416471971031L);SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String s = sdf.format(d);System.out.println(s);高级获取功能:* public String[] list():获取指定目录下的所有文件或者文件夹的名称数组* public File[] listFiles():获取指定目录下的所有文件或者文件夹的File数组*/
public class FileDemo {public static void main(String[] args) {// 指定一个目录File file = new File("e:\\");// public String[] list():获取指定目录下的所有文件或者文件夹的名称数组String[] strArray = file.list();for (String s : strArray) {System.out.println(s);}System.out.println("------------");// public File[] listFiles():获取指定目录下的所有文件或者文件夹的File数组File[] fileArray = file.listFiles();for (File f : fileArray) {System.out.println(f.getName());}}
}
-------------------例题
判断E盘目录下是否有后缀名为.jpg的文件,如果有,就输出此文件名称第一种
public class FileDemo {public static void main(String[] args) {// 封装e判断目录File file = new File("e:\\");// 获取该目录下所有文件或者文件夹的File数组File[] fileArray = file.listFiles();// 遍历该File数组,得到每一个File对象,然后判断for (File f : fileArray) {// 是否是文件if (f.isFile()) {// 继续判断是否以.jpg结尾if (f.getName().endsWith(".jpg")) {// 就输出该文件名称System.out.println(f.getName());}}}}
} 第二种* 要想实现这个效果,就必须学习一个接口:文件名称过滤器* public String[] list(FilenameFilter filter)* public File[] listFiles(FilenameFilter filter)*/
public class FileDemo2 {public static void main(String[] args) {// 封装e判断目录File file = new File("e:\\");// 获取该目录下所有文件或者文件夹的String数组// public String[] list(FilenameFilter filter)String[] strArray = file.list(new FilenameFilter() {@Overridepublic boolean accept(File dir, String name) {// return false;// return true;// 通过这个测试,我们就知道了,到底把这个文件或者文件夹的名称加不加到数组中,取决于这里的返回值是true还是false// 所以,这个的true或者false应该是我们通过某种判断得到的// System.out.println(dir + "---" + name);// File file = new File(dir, name);// // System.out.println(file);// boolean flag = file.isFile();// boolean flag2 = name.endsWith(".jpg");// return flag && flag2;return new File(dir, name).isFile() && name.endsWith(".jpg");}});// 遍历for (String s : strArray) {System.out.println(s);}}
}-----------------------------------递归* 分析:* 		A:封装目录* 		B:获取该目录下所有的文件或者文件夹的File数组* 		C:遍历该File数组,得到每一个File对象* 		D:判断该File对象是否是文件夹* 			是:回到B* 			否:继续判断是否以.java结尾* 				是:就输出该文件的绝对路径* 				否:不搭理它*/
public class FilePathDemo {public static void main(String[] args) {// 封装目录File srcFolder = new File("E:\\JavaSE");getAllJavaFilePaths(srcFolder);}private static void getAllJavaFilePaths(File srcFolder) {// 获取该目录下所有的文件或者文件夹的File数组File[] fileArray = srcFolder.listFiles();// 遍历该File数组,得到每一个File对象for (File file : fileArray) {// 判断该File对象是否是文件夹if (file.isDirectory()) {getAllJavaFilePaths(file);} else {// 继续判断是否以.java结尾if (file.getName().endsWith(".java")) {// 就输出该文件的绝对路径System.out.println(file.getAbsolutePath());}}}}
}------------------------------- IO 
IO流的分类:* 		流向:* 			输入流	读取数据* 			输出流 写出数据* 		数据类型:* 			字节流* 				字节输入流	读取数据	InputStream* 				字节输出流	写出数据	OutputStream* 			字符流* 				字符输入流	读取数据	Reader* 				字符输出流	写出数据	Writer* 字节:使用://创建文件FileOutputStream fos = new FileOutputStream("fos.txt");//写数据fos.write("hello,IO".getBytes());        显示:hello,IOfos.write("java".getBytes());                  javabyte[] bys ={97,98,99,100,101,101};           fos.write(bys);                                 abcde  (对应编码)fos.write(bys,1,3);                           bcd  (bys从1开始数3个)//释放资源//关闭此文件输出流并释放与此流有关的所有系统资源。fos.close();----------------追加写入FileOutputStream fos = new FileOutputStream("fos.txt",true);在文件末尾写入,添加。不加TURE则覆盖--------------------读FileInputStream fos = new FileInputStream("fos.txt");int by = 0;while((by=fos.read())!=-1){syso((char)by);}fis.close();------------------  COpy    
按每个字节(效率低)FileInputStream fos = new FileInputStream("fos.txt");FileOutputStream foos = new FileOutputStream("foos.txt");int by = 0;while((by=fis.read())!=-1){foos.write(by);}fos.close();foos.close();
按字节数组,效率高FileInputStream fis = new FileInputStream("e:\\哥有老婆.mp4");// 封装目的地FileOutputStream fos = new FileOutputStream("copy.mp4");// 复制数据byte[] bys = new byte[1024];int len = 0;while ((len = fis.read(bys)) != -1) {fos.write(bys, 0, len);}// 释放资源fos.close();fis.close();------高效法  public static void main(String[] args) throws IOException {method3("e:\\哥有老婆.mp4", "copy1.mp4");public static void method3(String srcString, String destString)throws IOException {BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcString));BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destString));---后面+单字节或者字节数组。 变成高效单字节和高效字节组---------------字符流InputStreamReader bis = new InputStreamReader(new FileInputStream(srcString),“UTF-8”);InputStreamWrite bis = new InputStreamWrite(new FileInputStream(srcString),“UTF-8”);     不+编码表就为默认编码表字符流操作之后要刷新缓冲区 close()和flush()的区别?* A:close()关闭流对象,但是先刷新一次缓冲区。关闭之后,流对象不可以继续再使用了。* B:flush()仅仅刷新缓冲区,刷新之后,流对象还可以继续使用。(大数据的时候用)简化写法:    FileReader    FileWrite  (属于字符流子类,一般不需要写编码,默认本地编码) FileReader fr = new  FileReader(“a.txt”);高效字符流   BufferedReader sd= new BufferedReader(new  FileReader(“a.txt”));----------------------按行读取(不算换行符。如不写**.newLine或者 print-ln 会挤在一起 )// 封装数据源BufferedReader br = new BufferedReader(new FileReader("a.txt"));// 封装目的地BufferedWriter bw = new BufferedWriter(new FileWriter("b.txt"));// 读写数据String line = null;while ((line = br.readLine()) != null) {bw.write(line);bw.newLine();bw.flush();}// 释放资源bw.close();br.close();-----------------------------复制文件夹并改名例题  CopyFolderDemo.java/ / 获取该目录下的java文件的File数组File[] fileArray = srcFolder.listFiles(new FilenameFilter() {public boolean accept(File dir, String name) {return new File(dir, name).isFile() && name.endsWith(".java");String里更换字符   replaceString name =destFile.getName(); //DataTypeDemo.javaString newName = name.replace(".java", ".jad");//DataTypeDemo.jad------------------------   带行号 文件读取输出初始化  LineNumberReader inr =new LineNumberReader (new File Reader("my.txt"));用: inr.setLineNumber(10);  //如果写了这句,那么下面行就直接从11开始。否则1String line = null;while ((line = br.readLine()) != null) {syso.(inr.getLineNumber()+line);   获取行号+每行数据