1 IO 流(I:Input O:Output)
1.1 File类(文件和目录)
- 作用:文件和目录路径名的抽象表示
public class TestFile {
@Test
public void test1() {
//操作文件
File f1=new File("d:/test/aa.txt"); //绝对路径:包含完整盼复的路径名称
File f2=new File("aa.txt"); //相对路径:相对于当前资源的路径
File f4=new File("d:/test/bb.txt");
//操作目录
File f3 =new File("d:/test/io");
System.out.println(f1.getName());//获取文件或者文件夹的名称
System.out.println(f1.getPath());//获得路径
System.out.println(f1.getAbsoluteFile());
System.out.println(f1.getAbsolutePath());
System.out.println(f1.getParent());
System.out.println("==========================");
System.out.println(f2.getName());//获取文件或者文件夹的名称
System.out.println(f2.getPath());//获得路径
System.out.println(f2.getAbsoluteFile());
System.out.println(f2.getAbsolutePath());
System.out.println(f2.getParent());
System.out.println("==========================");
System.out.println(f2.getName());//获取文件或者文件夹的名称
System.out.println(f2.getPath());//获得路径
System.out.println(f2.getAbsoluteFile());
System.out.println(f2.getAbsolutePath());
System.out.println(f2.getParent());
//renameTo(File newName) 原文件必须存在,新文件必须不存在
if(f1.renameTo(f4)) {
System.out.println("修改成功");
}else {
System.out.println("修改失败");
}
}
/*
文件检测 返回boolean
exists() 判断文件或目录是否存在
canWrite() 是否可写
canRead() 是否可读
isFile() 是否是一个文件
isDirectory 是否是一个目录
*/
@Test
public void test2(){
//操作文件
File f1=new File("d:/test/aa.txt"); //绝对路径:包含完整盼复的路径名称
File f2=new File("aa.txt"); //相对路径:相对于当前资源的路径
//操作目录
File f3 =new File("d:/test/io");
System.out.println(f1.exists()); //存在 返回true
System.out.println(f1.canWrite());
System.out.println(f1.canRead());
System.out.println(f1.isFile());
System.out.println(f1.isDirectory());
System.out.println(f3.isDirectory());
}
/*
获取常规文件信息
lastModified() 最后修改时间
length() 文件大小
文件操作相关
creatNewFile //创建新的文件
delete() //删除文件
mkDir() //创建目录 上级目录必须存在
mkDirs() //创建目录 上级目录可以不存在
list() //遍历当前目录下的文件返回文件的名称
listFiles //遍历当前目录下的文件返回文件对象
*/
@Test
public void test3() throws IOException {
//操作文件
File f1=new File("d:/test/aa.txt"); //绝对路径:包含完整盼复的路径名称
File f2=new File("aa.txt"); //相对路径:相对于当前资源的路径
File f4=new File("d:/test/bb.txt");
//操作目录
File f3 =new File("d:/test/io");
File f5=new File("d:/test/aa/bb/cc");
SimpleDateFormat sim = new SimpleDateFormat("yyyy-mm-dd");
//sim.formate(date);//将日期转String
//sim.parse(String); 将String 转日期
System.out.println(sim.format(new Date(f1.lastModified()))); //返回long类型(毫秒)
System.out.println(f1.length()); //字节
System.out.println(f4.createNewFile()?"创建成功":"创建失败");
if(f1.exists()) {
f4.delete();
}
//创建目录
boolean di = f5.mkdir(); //不能创建成功
boolean mkdirs = f5.mkdirs(); //可以创建
System.out.println(mkdirs); //true
System.out.println("=================");
File f6=new File("d:/test");
String[] list = f6.list();
System.out.println(Arrays.toString(list));
File[] listFiles = f6.listFiles();//[aa, aa.txt, io]
System.out.println(Arrays.toString(listFiles));//[d:\test\aa, d:\test\aa.txt, d:\test\io]
}
}
1.2 IO 原理
- IO流是不同设备见传递的数据
1.3 流的分类
-
三大类
- 按数据单位: 字节流(一般用于视频、音频文件等1字节=8bit)字符流(一般用于文本文件1字符=16bit)
- 按流向分类:输入流 输出流
- 按角色分类:节点流 处理流(缓存流)
各种流的关系
抽象父类 节点流(实现抽象类) 缓冲流(处理流)提高性能 字节流 InputStream(输入) FileInputStream BufferedInputStream OutputStream(输出) FileOutputStream BufferedOutputStream f 字符流 Reader(输入) FileReader BufferedReader Write(输出) FileWrite BufferedWrite -
FileInputStream
//hello.txt 中内容为:aaabbb public class TestFileStream { //读取文件(英文字符) 每次读取一定长度 //read(byte[] b) //从改输入流中读取最多b.length个字节的数据为字节数组 @Test public void Test3() throws IOException { FileInputStream fil=new FileInputStream("d:/test/hello.txt"); byte[] b=new byte[4]; int len; while((len=fil.read(b))!=-1) { //len每次读取字节的长度 String s=new String(b, 0, len); System.out.println(s); } fil.close(); } //读取文件(英文字符) //test改进 加一个循环 @Test public void test1() throws IOException { FileInputStream fil=new FileInputStream("d:/test/hello.txt"); int len; while((len=fil.read())!=-1) { System.out.print((char)len); } fil.close(); } //读取文件(英文字符) 每次读取一个 @Test public void test() throws IOException { FileInputStream fil=new FileInputStream("d:/test/hello.txt"); System.out.println((char)fil.read()); System.out.println((char)fil.read()); System.out.println((char)fil.read()); System.out.println((char)fil.read()); System.out.println((char)fil.read()); System.out.println("============="); } }
-
FileOutputStream
public class TestFileOutStream { //文件的复制 @Test public void test1() throws IOException { FileInputStream fis=new FileInputStream("d:/test/hello.txt");// 原文件 FileOutputStream fos=new FileOutputStream("d:/test/abc.txt");//目标文件 byte[] b=new byte[4]; int len; while((len=fis.read(b))!=-1) { //len每次读取字节的长度 fos.write(b, 0, len); } fos.close(); fis.close(); } //输出 @Test public void test() throws IOException { FileOutputStream fos=new FileOutputStream("aa.txt",false); fos.write("abcde".getBytes()); fos.close(); } }
-
FileReader、FileWrite
public class TestFileReader { //字符文件的复制 @Test public void test2() { FileReader fr = null; FileWriter fw = null; try { fr = new FileReader(new File("aa.txt")); fw = new FileWriter(new File("bb.txt")); char[] ch = new char[1024]; int len; while((len=fr.read(ch))!=-1) { fw.write(ch, 0, len); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if(fw!=null) fw.close(); if(fr!=null) fr.close(); } catch (IOException e) { e.printStackTrace(); } } } //读取字符文件 @Test public void test1() throws Exception { FileReader fr = new FileReader(new File("aaaa.doc")); char[] ch = new char[3]; int len; while((len=fr.read(ch))!=-1) { String s = new String(ch,0,len); System.out.print(s); } fr.close(); } }
1.4 缓冲流(效率高)
public class TestBufferedInputStream {
@Test
public void test2() {
long s = System.currentTimeMillis();
try {
test1();
} catch (Exception e1) {
e1.printStackTrace();
}
long e = System.currentTimeMillis();
System.out.println(e-s); //毫秒
}
//缓存流读/写
@Test
public void test1() throws Exception {
File file = new File("d:/1.wmv");
InputStream is = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(is);
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File("d:/3.wmv")));
byte[] bytes = new byte[1024];
int len;
while((len=bis.read(bytes))!=-1) {
bos.write(bytes, 0, len);
}
bos.close();
bis.close();
}
}
1.5 转换流(字节->字符)
-
将字节流转换为字符流
InputStreamReader
OutputStreamWriter
-
标准的输入流:InputStream is = System.in; //输入流
-
标准的输出流:printStream ps = System.out; //打印流
案例:接收键盘的输入,并且在控制台输出。
public class TestInputStremReaderWriter {
@Test
public void test1() throws UnsupportedEncodingException {
//字节输入流
InputStream is = System.in; //键盘标准 字节输入流
//字节流转字符流
// InputStreamReader isr = new InputStreamReader(is, "utf-8");
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line=null;
try {
line = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(line);
}
//模拟Scanner类
@Test
public void test2() {
// Scanner input = new Scanner(System.in);
// String next2 = input.next();
MyScanner ms = new MyScanner(System.in);
System.out.println("请输入姓名:");
String name = ms.next();
System.out.println("请输入年龄:");
int age = ms.nextInt();
System.out.println("请输入成绩:");
double score = ms.nextDouble();
ms.close(); //
System.out.println("信息:"+name+"====="+age+"====="+score);
}
}
//创建一个功能与Scanner类相似
class MyScanner{
InputStream is =null;
public MyScanner(InputStream is) {
this.is = is;
}
//接收用户输入字符串
public String next() {
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
try {
line = br.readLine();
} catch (IOException e) {
e.printStackTrace();
} finally {
// try {
// if(br!=null) {
// br.close();
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
}
return line;
}
//接收用户输入整数
public int nextInt() {
String str = next();
int num = Integer.parseInt(str);
return num;
}
//接收用户输入浮点数
public double nextDouble() {
String str = next();
double num = Double.parseDouble(str);
return num;
}
public void close() {
}
}
1.6 对象流(序列化和反序列化)
-
序列化:将对象的信息存储到文件中的这个过程叫序列化
ObjectOutputStream : writeObject(Object obj);
-
反序列化:将文件中的信息返回给类的对象的过程叫反序列化
ObjectInputSteram : readObject() //先写先读(第一次读的就是第一次写的对象)
public class TestObjectStream { //序列化(对象信息存储到文件) @Test public void test1() { Person p1 = new Person("小张",23); Person p2 = new Person("小明",19); FileOutputStream fos = null; ObjectOutputStream oos = null; try { fos = new FileOutputStream("d:/aa.abc"); oos = new ObjectOutputStream(fos); oos.writeObject(p1); oos.flush(); oos.writeObject(p2); oos.flush(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if(oos!=null) { oos.close(); } if(fos!=null) { fos.close(); } } catch (IOException e) { e.printStackTrace(); } } } //反序列化(将文件中的信息返回给对象 ) @Test public void test2() { FileInputStream fis = null; ObjectInputStream ois= null; try { fis = new FileInputStream(new File("d:/aa.abc")); ois = new ObjectInputStream(fis); Object o1 = ois.readObject(); Person p1 = (Person)o1; Object o2 = ois.readObject(); Person p2 = (Person)o2; System.out.println(p1+"======="+p2); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if(ois!=null) { ois.close(); } if(fis!=null) { fis.close(); } } catch (IOException e) { e.printStackTrace(); } } } } //人类 //如果要将某个的对象要进行序列化操作,必须对该实现Serializable class Person implements Serializable{ private static final long serialVersionUID = -3423423423442L; String name; int age; public Person() { super(); } public Person(String name, int age) { super(); this.name = name; this.age = age; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + "]"; } }
-
注意:
transient 、static修饰的属性不能被 序列化
1.7 数据流
-
DataInputStream 方法
readInt() readByte() readShort()
readLong() readChar() readBoolean()
readFloat() readDouble() readUTF()
-
DataOutputStream 方法
writeXxx(数据)
public class TestDateStream {
//写
@Test
public void Test1() throws Exception {
DataOutputStream dos = new DataOutputStream(new FileOutputStream("aaa.txt"));
dos.writeInt(1111);
dos.writeLong(12L);
dos.writeUTF("你好,1234,ABC$#%^&*()"); //utf
dos.flush();
dos.close();
}
//读
@Test
public void Test2() throws Exception {
DataInputStream dis = new DataInputStream(new FileInputStream("aaa.txt"));
int num = dis.readInt();
System.out.println(num);
long m = dis.readLong();
System.out.println(m);
String utf = dis.readUTF();
System.out.println(utf);
dis.close();
}
}
1.8 打印流
-
PrintStream<= System.out/System.err 默认在控制台输出内容
-
通过打印流向文件中输出内容
public class TestPrintStream { // PrintStream(OutputStream out, boolean autoFlush) // 创建一个新的打印流。 @Test public void test2() throws IOException { OutputStream os = new FileOutputStream("print.txt"); PrintStream ps = new PrintStream(os,true); //输出到文件 System.setOut(ps); System.out.println("abcd"); ps.close(); os.close(); } @Test public void test1() { PrintStream out = System.out; out.println("Hello"); } }
1.9 随机访问流
-
RandomAccessFile 类的实例支持读取和写入随机访问文件
public class TestRandomAccessFile { //插入 @Test public void test4() throws IOException { RandomAccessFile rw = new RandomAccessFile("print1.txt", "rw"); rw.seek(2); //第三个位置 abcdefg String line = rw.readLine(); //从当前光标开始一直这行结束 cdefg 此时光标在末尾 rw.seek(2); //重新移到到插入点 rw.write("zz".getBytes()); rw.write(line.getBytes()); rw.close(); } //替换 @Test public void test3() throws IOException { RandomAccessFile rw = new RandomAccessFile("print1.txt", "rw"); rw.seek(2); //第三个位置 abcd rw.write("zz".getBytes()); //abzz rw.close(); } //复制 @Test public void test2() throws IOException { //读文件 RandomAccessFile raf = new RandomAccessFile("print.txt", "r"); //写 RandomAccessFile rw = new RandomAccessFile("print1.txt", "rw"); //类似Stream操作 byte[] bytes = new byte[20]; int len; while((len=raf.read(bytes))!=-1) { //String s = new String(bytes,0,len); rw.write(bytes, 0, len); } rw.close(); raf.close(); } //读取文件信息 @Test public void test1() throws IOException { //读文件 RandomAccessFile raf = new RandomAccessFile("print.txt", "r"); //类似Stream操作 byte[] bytes = new byte[20]; int len; while((len=raf.read(bytes))!=-1) { String s = new String(bytes,0,len); System.out.print(s); } raf.close(); } }