java学习笔记(7)——I/O流

时间:2021-08-20 11:44:09
一、File类
File(File parent, String child);
File(Stirng filename);
--------------------------------------------------------
//使用相对路径创建文件和目录
package pack02;


import java.io.File;
import java.io.IOException;


public class FileTest {
public static void main(String[] args) throws IOException{
File file = new File("1.txt");
//file.createNewFile();
file.mkdir();
}
}
--------------------------------------------------
/**
 * 使用绝对路径创建文件或目录
 */
package pack02;


import java.io.File;
import java.io.IOException;


public class FileTest {
public static void main(String[] args) throws IOException{
File file = new File("E:\\javaTest\\lesson\\1.txt");
file.createNewFile();
}
}
------------------------------------------------------------
separator 用string类型表示分割符
separatorChar 用char类型表示分隔符
------------------------------------------------------------
/**
 * 不依赖系统平台的绝对路径
 */
package pack02;


import java.io.File;
import java.io.IOException;


public class FileTest {
public static void main(String[] args) throws IOException{
//可以直接用separator表示当前根目录
File fDir = new File(File.separator);
//E:\Javalesson\lesson7\1.txt
String strFile = "JavaLesson" + File.separator + "Lesson7"
+File.separator+"1.txt";
File f = new File(fDir, strFile);
f.createNewFile();
}
}
----------------------------------------------------------------
File f = new File(fDir, strFile);
f.createNewFile();
f.delete()   //删除文件
f.deleteOnExit()  //当程序终止的时候删除文件
-----------------------------------------------------------------
/**
 * 创建临时文件并在程序结束时删除该文件
 * 创建的临时文件在:
 * 我的电脑-->环境变量-->Temp(指定的目录)
 */
package pack02;


import java.io.File;
import java.io.IOException;


public class FileTest {
public static void main(String[] args) throws IOException{
for(int i=0;i<5;i++){
File f = File.createTempFile("winsun","temp");
f.deleteOnExit();
}
// try {
// Thread.sleep(3000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
}
}
------------------------------------------------------------------
list()方法:返回这个目录下的所有文件名和子目录名
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;


public class FileTest {
public static void main(String[] args) throws IOException{
String strFile = "E:"+File.separator+"A"+File.separator+"B"+File.separator;
File f = new File(strFile);
String[] names = f.list(new FilenameFilter(){
public boolean accept(File dir, String name) {
//System.out.println(dir);
return name.indexOf(".java") != -1;
}
});
for(String s:names){
System.out.println(s);
}
}
}
-------------------------------------------------------------------------
Decorater 装饰设计模式
节点流:从特定的地方读写的流。
过滤流:使用节点流作为输入或输出。
InputStream
abstract int read(); 读一个字节数据, 返回-1表示到了流的末尾
int read(byte[] b);   将数据读入字节数组 ,最后一次返回实际读取的字节数
int read(byte[] b, int off,  int len);  从指定位置读取, 最后一次返回实际读取的字节数
--------------------------------------------------------------------------
import java.io.*;
//将字符串写入文件
public class FileTest {
public static void main(String[] args) throws IOException{
FileOutputStream out = new FileOutputStream("1.txt");
out.write("http://www.baidu.com".getBytes());
out.close();
}
}
--------------------------------------------------------------------------
import java.io.*;
//将字符串从文件中读出
public class FileTest {
public static void main(String[] args) throws IOException{
FileOutputStream out = new FileOutputStream("1.txt");
out.write("http://www.baidu.com".getBytes());
out.close();
FileInputStream in = new FileInputStream("1.txt");
byte[] b = new byte[1024];
int len = in.read(b);
System.out.println(new String(b,0,len));
in.close();
}
}
--------------------------------------------------------------------------
import java.io.*;
//使用缓冲流写入数据到文件
public class FileTest {
public static void main(String[] args) throws IOException{
FileOutputStream out = new FileOutputStream("2.txt");
BufferedOutputStream bufOut = new BufferedOutputStream(out);
bufOut.write("http:www.baidu.com".getBytes());
bufOut.close(); //注意关闭的时候只需要关闭尾端的流
}
}
------------------------------------------------------------------------------
import java.io.*;
//使用缓冲流读出文件中数据
public class FileTest {
public static void main(String[] args) throws IOException{
FileOutputStream out = new FileOutputStream("2.txt");
BufferedOutputStream bufOut = new BufferedOutputStream(out);
bufOut.write("http:www.baidu.com".getBytes());
bufOut.close();
FileInputStream in = new FileInputStream("2.txt");
BufferedInputStream bufIn = new BufferedInputStream(in);
byte[] b = new byte[1024];
int len = bufIn.read(b);
System.out.println(new String(b,0,len));
bufIn.close();
}
}
-------------------------------------------------------------------------------
读取java中基本数据类型的类 DataInputStream()  DataOutputStream();
import java.io.*;
//使用Data过滤流读写
public class FileTest {
public static void main(String[] args) throws IOException{
FileOutputStream out = new FileOutputStream("2.txt");
BufferedOutputStream bufOut = new BufferedOutputStream(out);
DataOutputStream dataOut = new DataOutputStream(bufOut);
byte b = 3;
int i = 13;
char c = 'a';
float f = 12.3f;
dataOut.writeByte(b);
dataOut.writeInt(i);
dataOut.writeChar(c);
dataOut.writeFloat(f);
dataOut.close();
FileInputStream in = new FileInputStream("2.txt");
BufferedInputStream bufIn = new BufferedInputStream(in);
DataInputStream dataIn = new DataInputStream(bufIn);
byte b1 = dataIn.readByte();
int i1 = dataIn.readInt();
char c1 = dataIn.readChar();
float f1 = dataIn.readFloat();
System.out.println(b1);   //注意读和写的顺序必须一样,才能读对
System.out.println(i1);
System.out.println(c1);
System.out.println(f1);
dataIn.close();
}
}
------------------------------------------------------------------------
管道流  PipedInputStream  PipedOutputStream   他们总是成对出现的(注意这不是过滤流)
import java.io.*;
//使用Data过滤流读写
public class FileTest {

public static void main(String[] args) throws IOException{
PipedOutputStream pipOut = new PipedOutputStream();
PipedInputStream pipIn = new PipedInputStream();
pipOut.connect(pipIn);
new Produce(pipOut).start();
new Consumer(pipIn).start();
}

}
class Produce extends Thread{
private PipedOutputStream pipOut;
public Produce(PipedOutputStream pipOut){
this.pipOut = pipOut;
}
public void run(){
try {
pipOut.write("hello wellcome in file".getBytes());
pipOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Consumer extends Thread{
private PipedInputStream pipIn;
public Consumer(PipedInputStream pipIn){
this.pipIn = pipIn;
}
public void run(){
byte[] b = new byte[1024];
try {
int len = pipIn.read(b);
System.out.println(new String(b, 0, len));
} catch (IOException e) {
e.printStackTrace();
}
}
}
------------------------------------------------------------------------
上面是字节流,下面是字符流
OutputStreamWriter() 从字节流到字符流转换
InputStreamRead()  从字符流到字节流转换
通常使用Buffered流进行读写
-------------------------------------------------------------------------
import java.io.*;
//使用字符流读写数据
public class FileTest {

public static void main(String[] args) throws IOException{
FileOutputStream out = new FileOutputStream("3.txt");
OutputStreamWriter w = new OutputStreamWriter(out);
BufferedWriter bufW = new BufferedWriter(w);
bufW.write("http://www.baidu.com");
bufW.close();

FileInputStream in = new FileInputStream("3.txt");
InputStreamReader r = new InputStreamReader(in);
BufferedReader bufI = new BufferedReader(r);
String str = bufI.readLine();  //可以读一行
System.out.println(str);
bufI.close();
}
}
----------------------------------------------------------------------------
import java.io.*;
//从控制台输入并打印到控制台
public class FileTest {

public static void main(String[] args) throws IOException{
InputStreamReader in = new InputStreamReader(System.in);
BufferedReader bufIn = new BufferedReader(in);
String str;
while((str=bufIn.readLine()) != null){
System.out.println(str);
}
bufIn.close();
}
}
-----------------------------------------------------------------------------
ASCII :美国信息互换标准编码  是用一个字节来表示字符
GB2312:*汉子信息交换用码   一个中文用两个字节表示
GBK  :k是“扩展”   兼容GB2312,繁体,许多符号,不常用汉字编码
ISO-8859-1 :西方国家使用的字符编码,是一种单字节字符集,而英文只使用了小于128的部分
Unicode :通用的字符集,对所有语言的文字进行了统一的编码,每一个字符用两个字节来表示
但是对英文字符(一个字符用两个字节表示,浪费)
UTF-8 :通用字符集,英文用一个字节表示,是一种用适合长度字节表示不同字符。
-------------------------------------------------------------------------------
import java.io.*;
import java.nio.*;
import java.nio.charset.Charset;
import java.util.*;
//打印java中能够使用的所有的字符编码
public class FileTest {

public static void main(String[] args) throws IOException{
Map m = Charset.availableCharsets();
Set s = m.keySet();
Iterator i = s.iterator();
while(i.hasNext()){
System.out.println(i.next());
}
}
}
---------------------------------------------------------------------------------------
解码和编码
本地码----->其他编码(编码)
---------------------------------------------------------------------------------
/**
 * 从屏幕上读取虚拟机信息
 */
package pack02;


import java.util.Properties;


public class FileTest {
public static void main(String[] args){
Properties pps = System.getProperties();
pps.list(System.out);
}
}
-----------------------------------------------------------------------------------
/**
 * 改变虚拟机默认字符集,后从控制台读入解码,再编码为字符串输出
 */
package pack02;


import java.io.IOException;
import java.nio.Buffer;
import java.util.Properties;


import com.sun.jndi.url.iiopname.iiopnameURLContextFactory;


public class FileTest {
public static void main(String[] args) throws IOException{
Properties pps = System.getProperties();
pps.put("file.encoding", "ISO-8859-1");
int data;
byte[] b = new byte[1024];
int len = 0;
while((data=System.in.read()) != 'q'){
b[len] = (byte)data;
len ++;
}
String str = new String(b, 0, len);
System.out.println(str);
}
}
-----------------------------------------------------------------------------------
RandomAccessFile类


package pack02;


import java.io.IOException;
import java.io.RandomAccessFile;


class RandomFileTest{
public static void main(String[] args) throws Exception{
Student s1 = new Student(1,"zs",67);
Student s2 = new Student(2,"ls",89);
Student s3 = new Student(3,"wu",98);
RandomAccessFile raf = new RandomAccessFile("Student.txt","rw");
s1.writeStudent(raf);
s2.writeStudent(raf);
s3.writeStudent(raf);
Student s = new Student();
raf.seek(0);  //指向开始
//length()获取文件长度,  getFilePointer()一个指针
for(long i=0;i<raf.length();raf.getFilePointer()){
s.readStudent(raf);
System.out.println(s.name);
System.out.println(s.num);
System.out.println(s.score);
}
raf.close(); //关闭流
}
}
class Student{
int num;
String name;
double score;
public Student(){

}
public Student(int num,String name,double score){
this.num = num;
this.name = name;
this.score = score;
}
public void writeStudent(RandomAccessFile raf)throws IOException{
raf.writeInt(num);
raf.writeUTF(name); 
raf.writeDouble(score);
}
public void readStudent(RandomAccessFile raf) throws IOException{
num = raf.readInt();
name = raf.readUTF();
score = raf.readDouble();
}
}
----------------------------------------------------------------------------
对象序列化
将对象转换为字节流保存起来,并在日后还原这个对象,这种机制叫做对象序列
将一个对象保存到永久存储设备上称为持续性。
一个对象要想能够实现序列化,必须实现Serializable接口或Externalizable接口。
1.Serializable是一个空接口(没有方法)
2.Externalizable继承自Serializable接口
-----------------------------------------------------------------------------
package pack02;


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;


public class ObjectSerialTest {
public static void main(String[] args) throws IOException, ClassNotFoundException{
Employee e1 = new Employee("zhangsan",25,3000.5);
Employee e2 = new Employee("lisi",24,6000.5);
Employee e3 = new Employee("wangwu",45,60660.5);
FileOutputStream fos = new FileOutputStream("employee.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(e1);
oos.writeObject(e2);
oos.writeObject(e3);
oos.close();
FileInputStream fis = new FileInputStream("employee.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
Employee e;
for(int i=0;i<3;i++){
e =(Employee)ois.readObject();
System.out.println(e.name);
System.out.println(e.salary);
System.out.println(e.age);
}
ois.close();
}
}
class Employee implements Serializable{
String name;
int age;
double salary;
public Employee() {
super();
}
public Employee(String name, int age, double salary) {
super();
this.name = name;
this.age = age;
this.salary = salary;
}


}
-----------------------------------------------------------------------------
当一个对象被序列化时,只保存对象的非静态成员变量,不能保存任何的成员方法和静态的成员变量。
如果一个对象的成员变量是一个对象,那么这个对象的数据也会被保存。
如果一个可序列化的对象包含对某个不可序列化的对象的引用,那么整个序列化操作将会失败,
并且会抛出一个NotSerializableException.我们可以将这个引用标记为transient,那么对象任然可以序列化。
------------------------------------------------------------------------------
package pack02;


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;


public class ObjectSerialTest {
public static void main(String[] args) throws IOException, ClassNotFoundException{
Employee e1 = new Employee("zhangsan",25,3000.5);
Employee e2 = new Employee("lisi",24,6000.5);
Employee e3 = new Employee("wangwu",45,60660.5);
FileOutputStream fos = new FileOutputStream("employee.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(e1);
oos.writeObject(e2);
oos.writeObject(e3);
oos.close();
FileInputStream fis = new FileInputStream("employee.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
Employee e;
for(int i=0;i<3;i++){
e =(Employee)ois.readObject();
System.out.println(e.name);
System.out.println(e.salary);
System.out.println(e.age);
System.out.println(e.thread); //可以被序列化
}
ois.close();
}
}
class Employee implements Serializable{
String name;
int age;
double salary;
//Thread thread  = new Thread(); //不可序列化的对象
//加上transient后可以被序列化
//可以序列化的不想被序列化也可以在前面加上transient
transient Thread thread = new Thread();
public Employee() {
super();
}
public Employee(String name, int age, double salary) {
super();
this.name = name;
this.age = age;
this.salary = salary;
}
}
-----------------------------------------------------------------------------------
重写 readObject()和writeObject()方法
//这两个方法是一个特例,声明为private后在外面能被调用
private void  writeObject(java.io.ObjectOutputStream oos) throws IOException{
oos.writeInt(age);
oos.writeUTF(name);
System.out.println("wirte object);
}
private void readObject(java.io.ObjectInputStream ois) throws IOException{
age = ois.readInt();
name = ois.readUTF();
System.out.println("read object");
}