java Io 全解

java.lang.Object

  继承者 java.io.File

 boolean

canRead() 
          
测试应用程序是否可以读取此抽象路径名表示的文件。

 boolean

canWrite() 
          
测试应用程序是否可以修改此抽象路径名表示的文件。

 int

compareTo(File pathname) 
          
按字母顺序比较两个抽象路径名。

 boolean

createNewFile() 
          
当且仅当不存在具有此抽象路径名指定的名称的文件时,原子地创建由此抽象路径名指定的一个新的空文件。

static File

createTempFile(String prefix, String suffix) 
          
在默认临时文件目录中创建一个空文件,使用给定前缀和后缀生成其名称。

static File

createTempFile(String prefix, String suffix, File directory) 
           
在指定目录中创建一个新的空文件,使用给定的前缀和后缀字符串生成其名称。

 boolean

delete() 
          
删除此抽象路径名表示的文件或目录。

 void

deleteOnExit() 
          
在虚拟机终止时,请求删除此抽象路径名表示的文件或目录。

 boolean

equals(Object obj) 
          
测试此抽象路径名与给定对象是否相等。

 boolean

exists() 
          
测试此抽象路径名表示的文件或目录是否存在。

 File

getAbsoluteFile() 
          
返回抽象路径名的绝对路径名形式。

 String

getAbsolutePath() 
          
返回抽象路径名的绝对路径名字符串。

 File

getCanonicalFile() 
          
返回此抽象路径名的规范形式。

 String

getCanonicalPath() 
          
返回抽象路径名的规范路径名字符串。

 String

getName() 
          
返回由此抽象路径名表示的文件或目录的名称。

 String

getParent() 
          
返回此抽象路径名的父路径名的路径名字符串,如果此路径名没有指定父目录,则返回 null

 File

getParentFile() 
          
返回此抽象路径名的父路径名的抽象路径名,如果此路径名没有指定父目录,则返回 null

 String

getPath() 
          
将此抽象路径名转换为一个路径名字符串。

 int

hashCode() 
          
计算此抽象路径名的哈希码。

 boolean

isAbsolute() 
          
测试此抽象路径名是否为绝对路径名。

 boolean

isDirectory() 
          
测试此抽象路径名表示的文件是否是一个目录。

 boolean

isFile() 
          
测试此抽象路径名表示的文件是否是一个标准文件。

 boolean

isHidden() 
          
测试此抽象路径名指定的文件是否是一个隐藏文件。

 long

lastModified() 
          
返回此抽象路径名表示的文件最后一次被修改的时间。

 long

length() 
          
返回由此抽象路径名表示的文件的长度。

 String[]

list() 
          
返回由此抽象路径名所表示的目录中的文件和目录的名称所组成字符串数组。

 String[]

list(FilenameFilter filter) 
          
返回由包含在目录中的文件和目录的名称所组成的字符串数组,这一目录是通过满足指定过滤器的抽象路径名来表示的。

 File[]

listFiles() 
          
返回一个抽象路径名数组,这些路径名表示此抽象路径名所表示目录中的文件。

 File[]

listFiles(FileFilter filter) 
          
返回表示此抽象路径名所表示目录中的文件和目录的抽象路径名数组,这些路径名满足特定过滤器。

 File[]

listFiles(FilenameFilter filter) 
          
返回表示此抽象路径名所表示目录中的文件和目录的抽象路径名数组,这些路径名满足特定过滤器。

static File[]

listRoots() 
          
列出可用的文件系统根目录。

 boolean

mkdir() 
          
创建此抽象路径名指定的目录。

 boolean

mkdirs() 
          
创建此抽象路径名指定的目录,包括创建必需但不存在的父目录。

 boolean

renameTo(File dest) 
          
重新命名此抽象路径名表示的文件。

 boolean

setLastModified(long time) 
          
设置由此抽象路径名所指定的文件或目录的最后一次修改时间。

 boolean

setReadOnly() 
          
标记此抽象路径名指定的文件或目录,以便只可对其进行读操作。

 String

toString() 
          
返回此抽象路径名的路径名字符串。

 URI

toURI() 
          
构造一个表示此抽象路径名的 file: URI

 URL

toURL() 
          
将此抽象路径名转换成一个 file: URL

 

FileDemo

import java.util.*;

import java.io.*;

public class FileDemo {

    public static void main(String []args)throws IOException{

        Scanner scan=new Scanner(System.in);

        System.out.println("请输入文件或文件夹路径!");

        String path=scan.next();

        File file=new File(path);

        if(file.isFile()){

            System.out.printf("%s是文件\n",file.getName());

            System.out.printf("%s文件%s\n",file.getName(),file.canRead()?"可读":"不可读");

            System.out.printf("%s文件%s\n",file.getName(),file.canWrite()?"可写":"不可写");

            System.out.printf("该文件为%d个字节\n",file.length());

        }else if(file.isDirectory()){

            List<File> fileList=new ArrayList<File>();

            System.out.printf("%s是文件夹\n",file.getName());

            File[] files=file.listFiles();

            for(File tempFile:files){

                if(tempFile.isFile()){

                    fileList.add(tempFile);

               // System.out.printf("%s\n",tempFile.getName());

            }else{

                System.out.printf("&&&&[%s]&&&\n",tempFile.getName());

            }

            }

            for(File temfile:fileList){

                System.out.printf("%s\n",temfile.getName());

            }

        }else{

            System.out.printf("%s文件不存在",file.getName());

            file.mkdirs();

 

        }

    }

}

 

java.lang.Object
  继承者 java.io.RandomAccessFile

一个字符两个字节

一个字节八位

Int类型占4个字节

文件存取通常是循序的,每在文件中存取一次,文件的读取位置就会相对于目前的位置前进一次.然而有时必须制定文件的某个区段进行读取或写入的动作,也就是进行随机存取(RandomAccess),即要能在文件中随意第移动读取位置.这时可以使用RandomAccessFile,使用它的seek()方法来指定文件存取的位置,指定的单位是字节.

为了移动存取位置时的方便,通常在随机存取文件中会固定每一个数据的长度.例如长度固定为每一个学生个人的数据,Java中并没有直接的方法可以写入一个固定长度数据,所以在固定每一个长度方面必须自行设计.

File file=new File(args[0]);

//建立RandomAccessFile实例并以读写模式开启文件

RandomAccessFile randomAccessFile=newRandomAccessFile(file,"rw");

for(int i=0;i<students.length;i++){

    //使用对应的write方法写入数据

    randomAccessFile.writeChars(students[i].getName());

    randomAccessFile.writeInt(students[i].getScore());

}

 

//使用seek()方法操作存取位置

randomAccessFile.seek((num-1)*Student.size());

Student stuent=new Student();

//使用对应的read方法读出数据

stuent.setName(readName(randomAccessFile));

stuent.setScore(randomAccessFile.readInt());

System.out.println("姓名:"+student.getName());

System.out.println("分数:"+student.getScore());

//设定关闭文件

randomAccessFile.close();

private static String readName(RandomAccessFile randomAccessfile)throws IOException{

    char[]name=new char[15];

    for(int i=0;i<name.length;i++)

        name[i]=randomAccessfile.readChar();

    //将空字符取代为空格符并传回

    return new String(name).replace('\0','');

}

 

java.lang.StringBuilder

用来累加字符串,一个可变的字符序列。此类提供一个与 StringBuffer 兼容的 API,但不保证同步。该类被设计用作 StringBuffer 的一个简易替换,用在字符串缓冲区被单个线程使用的时候(这种情况很普遍)。如果可能,建议优先采用该类,因为在大多数实现中,它比 StringBuffer 要快。

 StringBuilder 上的主要操作是 append  insert 方法,可重载这些方法,以接受任意类型的数据。每个方法都能有效地将给定的数据转换成字符串,然后将该字符串的字符追加或插入到字符串生成器中。append 方法始终将这些字符添加到生成器的末端;而 insert方法则在指定的点添加字符。

例如,如果 z 引用一个当前内容为 "start" 的字符串的生成器对象,则该方法调用 z.append("le") 将使字符串生成器包含 "startle",而 z.insert(4, "le") 将更改字符串生成器,使之包含 "starlet"

 

 void

close() 
          
关闭此随机存取文件流并释放与该流关联的所有系统资源。

 FileChannel

getChannel() 
          
返回与此文件关联的惟一 FileChannel 对象。

 FileDescriptor

getFD() 
          
返回与此流关联的不透明文件描述符对象。

 long

getFilePointer() 
          
返回此文件中的当前偏移量。

 long

length() 
          
返回此文件的长度。

 int

read() 
          
从此文件中读取一个数据字节。

 int

read(byte[] b) 
          
将最多 b.length 个数据字节从此文件读入字节数组。

 int

read(byte[] b, int off, int len) 
          
将最多 len 个数据字节从此文件读入字节数组。

 boolean

readBoolean() 
          
从此文件读取一个 boolean

 byte

readByte() 
          
从此文件读取一个有符号的八位值。

 char

readChar() 
          
从此文件读取一个 Unicode 字符。

 double

readDouble() 
          
从此文件读取一个 double

 float

readFloat() 
          
从此文件读取一个 float

 void

readFully(byte[] b) 
          
 b.length 个字节从此文件读入字节数组,并从当前文件指针开始。

 void

readFully(byte[] b, int off, int len) 
          
将正好 len 个字节从此文件读入字节数组,并从当前文件指针开始。

 int

readInt() 
          
从此文件读取一个有符号的 32 位整数。

 String

readLine() 
          
从此文件读取文本的下一行。

 long

readLong() 
          
从此文件读取一个有符号的 64 位整数。

 short

readShort() 
          
从此文件读取一个有符号的 16 位数。

 int

readUnsignedByte() 
          
从此文件读取一个无符号的八位数。

 int

readUnsignedShort() 
          
从此文件读取一个无符号的 16 位数。

 String

readUTF() 
          
从此文件读取一个字符串。

 void

seek(long pos) 
          
设置到此文件开头测量到的文件指针偏移量,在该位置发生下一个读取或写入操作。

 void

setLength(long newLength) 
          
设置此文件的长度。

 int

skipBytes(int n) 
          
尝试跳过输入的 n 个字节以丢弃跳过的字节。

 void

write(byte[] b) 
          
 b.length 个字节从指定字节数组写入到此文件,并从当前文件指针开始。

 void

write(byte[] b, int off, int len) 
          
 len 个字节从指定字节数组写入到此文件,并从偏移量 off 处开始。

 void

write(int b) 
          
向此文件写入指定的字节。

 void

writeBoolean(boolean v) 
          
按单字节值将 boolean 写入该文件。

 void

writeByte(int v) 
          
按单字节值将 byte 写入该文件。

 void

writeBytes(String s) 
          
按字节序列将该字符串写入该文件。

 void

writeChar(int v) 
          
按双字节值将 char 写入该文件,先写高字节。

 void

writeChars(String s) 
          
按字符序列将一个字符串写入该文件。

 void

writeDouble(double v) 
          
使用 Double 类中的 doubleToLongBits 方法将双精度参数转换为一个 long,然后按八字节数量将该 long 值写入该文件,先定高字节。

 void

writeFloat(float v) 
          
使用 Float 类中的 floatToIntBits 方法将浮点参数转换为一个 int,然后按四字节数量将该 int 值写入该文件,先写高字节。

 void

writeInt(int v) 
          
按四个字节将 int 写入该文件,先写高字节。

 void

writeLong(long v) 
          
按八个字节将 long 写入该文件,先写高字节。

 void

writeShort(int v) 
          
按两个字节将 short 写入该文件,先写高字节。

 void

writeUTF(String str) 
          
使用 modified UTF-8 编码以与机器无关的方式将一个字符串写入该文件。

 

RandomAccessFileDemo

import java.util.*;

import java.io.*;

public class RandomAccessFileDemo{

    public static void main (String []args )throws FileNotFoundException,IOException{

        Student s1=new Student("tom",20);

        Student s2=new Student("Jack",30);

        Student s3=new Student("zhang3",20);

        Student s4=new Student("Liudehua",10);

        Student[] students={s1,s2,s3,s4};

        Scanner scan=new Scanner(System.in);

        System.out.println("请输入一个文件路径!");

        String path=scan.next();

        //RandomAccessFile工具,File文件建立关联,即打开File文件,RW(读写)形式打开

        RandomAccessFile raf=new RandomAccessFile(new File(path),"rw");

        for(Student student:students){

            raf.writeChars(student.getName());

            raf.writeInt(student.getAge());

        }

       

        System.out.println("请选择1-4的学生");

        int count=scan.nextInt();

        raf.seek((count-1)*Student.getSize());

        char[]chars=new char[10];

        for(int i=0;i<10;i++){

            chars[i]=raf.readChar();

        }

        String name=String.valueOf(chars);

        int age=raf.readInt();

        System.out.printf("%d个学生的名字为%s,年龄为%d",count,name,age);

        raf.close();

    }

}

 

java.lang.Object
  继承者 java.io.InputStream
      

  继承者 java.io.InputStreamjava.io.OutputStream

计算机中的数据都是以01的方式来存储,如果要在两个装置之间进行数据的存取,当然也是以01位的方式来进行,Java将数据于目的地及来源之间的流动抽象华为一个流(Stream),而流当中流动的则是位数据.

流里面放的都是01,由于位是由于01来表示的,所以叫做位流.

数据流动抽象化为一个串流(Stream)

InputStream是所有表示位输入串流的类之父类

System中的标准输入串流in对象就是一个InputStream类型的实例

OutputSream是所有表示位输出串流的类之父类

System中的标准输出串流对象out其类型是java.io.PrintSream,OutputStream的子类.

很少直接操作InputStreamOutputStream上的方法,这些方法比较低阶

通常会操作它们的子类:

System.out.println(“输入字符十进制表示:”+System.in.read());

建立FileInputSreamFileOutputStream的实例时,必须制定文件位置及文件名,实例被创建时文件的串流就会开启.

不适用串流时,必须关闭文件串流,以释放与串流相依的系统资源.

FileInputStream fileInputStream=new FileInputStream(new File(srgs[0]));

FileOutputStream fileOutputStream=new FileOutputStream(new File(args[1]));

...

fileInputStream.close();

fileOutputStream.close();

 

 

while(true)

{

    if(fileInputStream.available()<1024)

    {

        //剩余的资料比1024

        //一位一位读出再写入目标文件

        int remain=-1;

        while((remain=fileInputStream.read())!=-1)

        {

            fileOutputStream.write(remain);

        }

        break;

    }else

    {  

        //从来源文件读取数据至缓存区

        fileInputStream.read(buffer);

        //将数组数据写入目标文件

        fileOutputStream.write(buffer);

    }

}

 

 FileInputStream方法摘要

 

 int

available() 
          
返回可以不受阻塞地从此文件输入流中读取的字节数。

 void

close() 
          
关闭此文件输入流并释放与此流有关的所有系统资源。

protected void

finalize() 
          
确保在不再引用文件输入流时调用其 close 方法。

 FileChannel

getChannel() 
          
返回与此文件输入流有关的惟一 FileChannel 对象。

 FileDescriptor

getFD() 
          
返回表示到文件系统中实际文件的连接的 FileDescriptor 对象,该文件系统正被此 FileInputStream 使用。

 int

read() 
          
从此输入流中读取一个数据字节。

 int

read(byte[] b) 
          
从此输入流中将最多 b.length 个字节的数据读入一个字节数组中。

 int

read(byte[] b, int off, int len) 
          
从此输入流中将最多 len 个字节的数据读入一个字节数组中。

 long

skip(long n) 
          
从输入流中跳过并丢弃 n 个字节的数据。

 

 FileOutputStream方法摘要

 

 void

close() 
          
关闭此文件输出流并释放与此流有关的所有系统资源。

protected void

finalize() 
          
清理到文件的连接,并确保在不再引用此文件输出流时调用此流的 close 方法。

 FileChannel

getChannel() 
          
返回与此文件输出流有关的惟一 FileChannel 对象。

 FileDescriptor

getFD() 
          
返回与此流有关的文件描述符。

 void

write(byte[] b) 
          
 b.length 个字节从指定字节数组写入此文件输出流中。

 void

write(byte[] b, int off, int len) 
          
将指定字节数组中从偏移量 off 开始的 len 个字节写入此文件输出流。

 void

write(int b) 
          
将指定字节写入此文件输出流。

 

import java.util.*;

import java.io.*;

public class FileStreamDemo{

    public static void main(String[]args) throws FileNotFoundException,IOException{

        Scanner scan=new Scanner(System.in);

        System.out.println("请输入你要复制的文件");

        String inPath=scan.next();

        System.out.println("请输入你要复制到哪里");

        String outPath=scan.next();

        File inFile=new File(inPath);

        //创建FileInputStream对象,FIle文件关联;

        FileInputStream fis=new FileInputStream(inFile);

        //创建FileOutputStream对象,outPath文件关联;

        FileOutputStream fos=new FileOutputStream(new File(outPath));

        System.out.println("开始复制");

        long startTime=System.currentTimeMillis();

        /*for(int i=0;i<=inFile.length();i++){

            int flag=fis.read();

            fos.write(flag);

        }*/

        /*int flag=-1;

        while((flag=fis.read())>=0){

            fos.write(flag);

        }*/

        byte[] buffer=new byte[1024*20];

        while(true){

            if(fis.available()<1024*20){

                int flag=fis.read();

                if(flag<0)break;

                fos.write(flag);

            }

            fis.read(buffer);

            fos.write(buffer);

        }

        long endTime=System.currentTimeMillis();

        System.out.println("复制完毕");

        System.out.printf("用时%d",endTime-startTime);

        fis.close();

        fos.close();

    }

}

 

java.io.InputStream
      继承者 java.io.FilterInputStream    
BufferedInputStreamBufferedOutputStream
 BufferedInputStream的资料成员buf是个位数组,默认为2048字节

BufferedOutputStream的资料成员buf是个位数组,默认为512个字节.

BufferedInputStream bufferedInputStream=new BufferedInputStream(new FileInputStream(srcFile));

BufferedOutputStream bufferedOutputStream=new BufferedOutputStream(new FileOutputStream(desFile));

System.out.println("复制文件:"+srcFile.length()+"字节");

while(bufferedInputStream.read(data)!=-1){

    bufferedOutputStream.write(data);

}

//将缓冲区中的数据全部写出

bufferedOutputStream.flush();

//关闭串流

bufferedInputStream.close();

bufferedOutputStream.close();

 

BufferedInputStream方法摘要

 int

available() 
          
返回可以不受阻塞地从此输入流读取的字节数。

 void

close() 
          
关闭此输入流并释放与该流关联的所有系统资源。

 void

mark(int readlimit) 
          
参见 InputStream  mark 方法的常规协定。

 boolean

markSupported() 
          
测试此输入流是否支持 mark  reset 方法。

 int

read() 
          
参见 InputStream  read 方法的常规协定。

 int

read(byte[] b, int off, int len) 
          
在此字节输入流中从给定的偏移量开始将各字节读取到指定的 byte 数组中。

 void

reset() 
          
参见 InputStream  reset 方法的常规协定。

 long

skip(long n) 
          
参见 InputStream  skip 方法的常规协定。

 

 BufferedOutputStream方法摘要

void

flush() 
          
刷新此缓冲的输出流。

 void

write(byte[] b, int off, int len) 
          
将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此缓冲的输出流。

 void

write(int b) 
          
将指定的字节写入此缓冲的输出流。

 

import java.util.*;

import java.io.*;

public class BufferedStreamDemo{

    public static void main(String []args) throws FileNotFoundException,IOException{

         Scanner scan=new Scanner(System.in);

        System.out.println("请输入文件路径!");

        String inPath=scan.next();

        System.out.println("请输入存放路径!");

        String outPath=scan.next();

        File inFile=new File(inPath);

       

        BufferedInputStream bin=new BufferedInputStream(new FileInputStream(new File(inPath)));

        BufferedOutputStream bout=new BufferedOutputStream(new FileOutputStream(new File(outPath)));

        System.out.println("开始复制");

        long startTime=System.currentTimeMillis();

        byte[] data=new byte[1];

        while((bin.read(data))!=-1){

            bout.write(data);

        }

        long endTime=System.currentTimeMillis();

        System.out.println("复制完毕");

        System.out.printf("用时%d",(endTime-startTime)/1000);

        bin.close();

        bout.close();

    }

}

 

java.io.InputStream
      继承者 java.io.FilterInputStream          继承者 

DataInputStreamDataOutputStream

主要是对java的基本数据类型,以及字符串提供的一些读写操作

数据输出流允许应用程序以适当方式将基本 Java 数据类型写入输出流中。然后,应用程序可以使用数据输入流将数据读入。

提供一些对java基本数据型态写入的方法

DataOutputStream dataOutputStream=new DataOutputStream(new FileOutputStream(args[0]));

for(Member member:member)

{

    //写入UTF字符串

    dataOutputStream.writeUTF(member.getName());

    //写入int资料

    dataOutputStream.writeInt(member.getAge());

}

    //清除所有数据至目的地

    dataOutputStream.flush();

    //关闭串流

    dataOutputStream.close();

 

DataInputStream dataInputStream=new DataInputStream(new FileInputStream(args[0]));

//读出数据并还原为对象

for(int i=0;i<members.length;i++){

    //读出UTF字符串

    String name=dataInputStream.readUTF();

    //读出int资料

    int score=dataInputStream.readInt();

    members[i]=new member(name,score);

}

//关闭串流

dataInputStream.close();

 

 DataInputStream方法摘要

 int

read(byte[] b) 
          
从所包含的输入流中读取一定数量的字节,并将它们存储到缓冲区数组 b 中。

 int

read(byte[] b, int off, int len) 
          
从所包含的输入流中将 len 个字节读入一个字节数组中。

 boolean

readBoolean() 
          
参见 DataInput  readBoolean 方法的常规协定。

 byte

readByte() 
          
参见 DataInput  readByte 方法的常规协定。

 char

readChar() 
          
参见 DataInput  readChar 方法的常规协定。

 double

readDouble() 
          
参见 DataInput  readDouble 方法的常规协定。

 float

readFloat() 
          
参见 DataInput  readFloat 方法的常规协定。

 void

readFully(byte[] b) 
          
参见 DataInput  readFully 方法的常规协定。

 void

readFully(byte[] b, int off, int len) 
          
参见 DataInput  readFully 方法的常规协定。

 int

readInt() 
          
参见 DataInput  readInt 方法的常规协定。

 String

readLine() 
          
已过时。 该方法无法将字节正确转换为字符。从 JDK 1.1 开始,读取文本行的首选方法是使用 BufferedReader.readLine() 方法。对于使用 DataInputStream 类读取文本行的程序,可以转而使用 BufferedReader 类,实现方式是通过将以下形式的代码:

     DataInputStream d = new DataInputStream(in);
 

替换为:

     BufferedReader d
          = new BufferedReader(new InputStreamReader(in));
 

 long

readLong() 
          
参见 DataInput  readLong 方法的常规协定。

 short

readShort() 
          
参见 DataInput  readShort 方法的常规协定。

 int

readUnsignedByte() 
          
参见 DataInput  readUnsignedByte 方法的常规协定。

 int

readUnsignedShort() 
          
参见 DataInput  readUnsignedShort 方法的常规协定。

 String

readUTF() 
          
参见 DataInput  readUTF 方法的常规协定。

static String

readUTF(DataInput in) 
          
从流 in 中读取用 UTF-8 修改版格式编码的 Unicode 字符格式的字符串;然后以 String 形式返回此字符串。

 int

skipBytes(int n) 
          
参见 DataInput  skipBytes 方法的常规协定。

 

 DataOutputStream方法摘要

void

flush() 
          
清空此数据输出流。

 int

size() 
          
返回计数器 written 的当前值,即到目前为止写入此数据输出流的字节数。

 void

write(byte[] b, int off, int len) 
          
将指定字节数组中从偏移量 off 开始的 len 个字节写入基础输出流。

 void

write(int b) 
          
将指定字节(参数 b 的八个低位)写入基础输出流。

 void

writeBoolean(boolean v) 
          
将一个 boolean 值以 1-byte 值形式写入基础输出流。

 void

writeByte(int v) 
          
将一个 byte 值以 1-byte 值形式写出到基础输出流中。

 void

writeBytes(String s) 
          
将字符串按字节顺序写出到基础输出流中。

 void

writeChar(int v) 
          
将一个 char 值以 2-byte 值形式写入基础输出流中,先写入高字节。

 void

writeChars(String s) 
          
将字符串按字符顺序写入基础输出流。

 void

writeDouble(double v) 
          
使用 Double 类中的 doubleToLongBits 方法将 double 参数转换为一个 long 值,然后将该 long 值以 8-byte 值形式写入基础输出流中,先写入高字节。

 void

writeFloat(float v) 
          
使用 Float 类中的 floatToIntBits 方法将 float 参数转换为一个 int 值,然后将该 int 值以 4-byte 值形式写入基础输出流中,先写入高字节。

 void

writeInt(int v) 
          
将一个 int 值以 4-byte 值形式写入基础输出流中,先写入高字节。

 void

writeLong(long v) 
          
将一个 long 值以 8-byte 值形式写入基础输出流中,先写入高字节。

 void

writeShort(int v) 
          
将一个 short 值以 2-byte 值形式写入基础输出流中,先写入高字节。

 void

writeUTF(String str) 
          
以与机器无关方式使用 UTF-8 修改版编码将一个字符串写入基础输出流。

 

import java.util.*;

import java.io.*;

public class DataStreamDemo{

    public static void main(String []args) throws Exception{

        Student s1=new Student("Aldrich",25);

        Student s2=new Student("zhangsan",34);

        Student s3=new Student("lisi",23);

        Student s4=new Student("wangwu",12);

        Student s5=new Student("zhaoliu",21);

        Student[] Students={s1,s2,s3,s4,s5};

        Scanner scan=new Scanner(System.in);

        System.out.println("请输入一个文件!");

        String path=scan.next();

        DataOutputStream dout=new DataOutputStream(new FileOutputStream(new File(path)));

        DataInputStream din=new DataInputStream(new FileInputStream(new File(path)));

        for(Student student:Students){

                dout.writeUTF(student.getName());

                dout.writeInt(student.getAge());

        }

        dout.flush();

        for(int i=0;i<5;i++){

            String name=din.readUTF();

            int age=din.readInt();

            System.out.printf("%d个学生的名字为%s,年龄是%d\n",i+1,name,age);

        }

        din.close();

        dout.close();

    }

}

java.io.InputStream

ObjectInputStreamObjectOutputStream

ObjectOutputStream  Java 对象的基本数据类型和图形写入 OutputStream。可以使用 ObjectInputStream 读取(重构)对象。通过使用流中的文件可以实现对象的持久存储。如果流是网络套接字流,则可以在另一台主机上或另一个进程中重构对象。

ObjectInputStream 对以前使用 ObjectOutputStream 写入的基本数据和对象进行反序列化。

对对象直接进行读写操作

把能够实现Serializable接口的对象,表示这个对象可序列化或可串行化的

要直接储存对象,定义该对象的类必须实现java.io.Serializable接口

public class User implements Serializable

{

    private static final long serialVersionUID=1L;

    ...

}

serialVersionUID代表了可串行化对象版本,从文件读回对象时两个对象的serialVersionUID不相同的话,就会丢出java.io.InvalidClassException

 ObjectInputStream方法摘要

 

 int

available() 
          
返回可以不受阻塞地读取的字节数。

 void

close() 
          
关闭输入流。

 void

defaultReadObject() 
          
从此流读取当前类的非静态和非瞬态字段。

protected  boolean

enableResolveObject(boolean enable) 
          
启用允许从要替代的流读取对象的流。

 int

read() 
          
读取数据字节。

 int

read(byte[] buf, int off, int len) 
          
读入字节数组。

 boolean

readBoolean() 
          
 boolean 形式读取。

 byte

readByte() 
          
读取一个 8 位的字节。

 char

readChar() 
          
读取一个 16 位的 char 值。

protected  ObjectStreamClass

readClassDescriptor() 
          
从序列化流读取类描述符。

 double

readDouble() 
          
读取一个 64 位的 double 值。

 ObjectInputStream.GetField

readFields() 
          
按名称从流中读取持久字段并使其可用。

 float

readFloat() 
          
读取一个 32 位的 float 值。

 void

readFully(byte[] buf) 
          
读取字节,在读取所有字节前将发生阻塞。

 void

readFully(byte[] buf, int off, int len) 
          
读取字节,在读取所有字节之前将发生阻塞。

 int

readInt() 
          
读取一个 32 位的 int 值。

 String

readLine() 
          
已过时。 此方法不能正确地将字节转换为字符。请参见 DataInputStream 以获取详细信息和替代方法。

 long

readLong() 
          
读取一个 64 位的 long 值。

 Object

readObject() 
          
 ObjectInputStream 读取对象。

protected  Object

readObjectOverride() 
          
此方法由使用受保护的无参数构造方法构造 ObjectOutputStream  ObjectOutputStream 的受信任子类调用。

 short

readShort() 
          
读取一个 16 位的 short 值。

protected  void

readStreamHeader() 
          
提供的 readStreamHeader 方法允许子类读取并验证它们自己的流头部。

 Object

readUnshared() 
          
 ObjectInputStream 读取非共享对象。

 int

readUnsignedByte() 
          
读取一个无符号的 8 位字节。

 int

readUnsignedShort() 
          
读取一个无符号的 16  short 值。

 String

readUTF() 
          
读取 UTF-8 修改版格式的 String

 void

registerValidation(ObjectInputValidation obj, int prio) 
          
在返回图形前注册要验证的对象。

protected  Class<?>

resolveClass(ObjectStreamClass desc) 
          
加载指定流类描述的本地等价类。

protected  Object

resolveObject(Object obj) 
          
在反序列化期间,此方法允许 ObjectInputStream 的受信任子类使用一个对象替代另一个。

protected  Class<?>

resolveProxyClass(String[] interfaces) 
          
返回一个代理类,该类实现在代理类描述符中命名的接口;子类可以实现此方法,以便从流及动态代理类的描述符中读取自定义数据,允许它们使用接口和代理类的替换加载机制。

 int

skipBytes(int len) 
          
跳过字节,在跳过所有字节之前将发生阻塞。

 

 ObjectOutputStream方法摘要

protected void

annotateClass(Class<?> cl) 
          
子类可以实现此方法,从而允许在流中存储类数据。

protected void

annotateProxyClass(Class<?> cl) 
          
一些子类可以实现此方法,从而在流中存储定制数据和动态代理类的描述符。

 void

close() 
          
关闭流。

 void

defaultWriteObject() 
          
将当前类的非静态和非瞬态字段写入此流。

protected void

drain() 
          
排空 ObjectOutputStream 中的所有已缓冲数据。

protected boolean

enableReplaceObject(boolean enable) 
          
允许流对流中的对象进行替换。

 void

flush() 
          
刷新该流的缓冲。

 ObjectOutputStream.PutField

putFields() 
          
检索用于缓冲写入流中的持久存储字段的对象。

protected Object

replaceObject(Object obj) 
          
在序列化期间,此方法允许 ObjectOutputStream 的受信任子类使用一个对象替代另一个对象。

 void

reset() 
          
重置将丢弃已写入流中的所有对象的状态。

 void

useProtocolVersion(int version) 
          
指定要在写入流时使用的流协议版本。

 void

write(byte[] buf) 
          
写入一个字节数组。

 void

write(byte[] buf, int off, int len) 
          
写入字节的子数组。

 void

write(int val) 
          
写入一个字节。

 void

writeBoolean(boolean val) 
          
写入一个 boolean 值。

 void

writeByte(int val) 
          
写入一个 8 位字节。

 void

writeBytes(String str) 
          
以字节序列形式写入一个 String

 void

writeChar(int val) 
          
写入一个 16 位的 char 值。

 void

writeChars(String str) 
          
 char 序列形式写入一个 String

protected void

writeClassDescriptor(ObjectStreamClass desc) 
          
将指定的类描述符写入 ObjectOutputStream

 void

writeDouble(double val) 
          
写入一个 64 位的 double 值。

 void

writeFields() 
          
将已缓冲的字段写入流中。

 void

writeFloat(float val) 
          
写入一个 32 位的 float 值。

 void

writeInt(int val) 
          
写入一个 32 位的 int 值。

 void

writeLong(long val) 
          
写入一个 64 位的 long 值。

 void

writeObject(Object obj) 
          
将指定的对象写入 ObjectOutputStream

protected void

writeObjectOverride(Object obj) 
          
子类用于重写默认 writeObject 方法的方法。

 void

writeShort(int val) 
          
写入一个 16 位的 short 值。

protected void

writeStreamHeader() 
          
提供 writeStreamHeader 方法,这样子类可以将其部分追加或预加到流中。

 void

writeUnshared(Object obj) 
          
未共享对象写入 ObjectOutputStream

 void

writeUTF(String str) 
          
 UTF-8 修改版格式写入此 String 的基本数据。

 

import java.util.*;

import java.io.*;

public class ObjectStreamDemo{

    public static void main(String[]args)throws Exception{

        Student s1=new Student("tom",20);

        Student s2=new Student("Jack",30);

        Student s3=new Student("zhang3",20);

        Student s4=new Student("Liudehua",10);

        Student[]students={s1,s2,s3,s4};

        Scanner scan =new Scanner(System.in);

        System.out.println("请输入一个路径!");

        String path=scan.next();

        ObjectOutputStream oout=new ObjectOutputStream(new FileOutputStream(new File(path)));

        ObjectInputStream oin=new ObjectInputStream(new FileInputStream(new File(path)));

        for(Student student:students){

            oout.writeObject(student);

        }

        oout.flush();

        for(int i=0;i<4;i++){

            Student student=(Student)oin.readObject();

            System.out.printf("%d个学生的名字为%s,年龄为%d\n",i+1,student.getName(),student.getAge());

        }

        oout.close();

        oin.close();

    }

}

java.util.Dictionary<K,V>
      继承者 java.util.Hashtable<Object,Object>

Properties

Properties 类表示了一个持久的属性集。Properties 可保存在流中或从流中加载。属性列表中每个键及其对应值都是一个字符串。

属性文件的读写

properties为扩展名的文件叫属性文件

key=value的形式(value不用用引号)

#为单行注释

java.util.Properties

load()加载属性文件

getProperty("key")获取value

 Properties方法摘要

 String

getProperty(String key) 
          
用指定的键在此属性列表中搜索属性。

 String

getProperty(String key, String defaultValue) 
          
用指定的键在属性列表中搜索属性。

 void

list(PrintStream out) 
          
将属性列表输出到指定的输出流。

 void

list(PrintWriter out) 
          
将属性列表输出到指定的输出流。

 void

load(InputStream inStream) 
          
从输入流中读取属性列表(键和元素对)。

 void

loadFromXML(InputStream in) 
          
将指定输入流中由 XML 文档所表示的所有属性加载到此属性表中。

 void

save(OutputStream out, String comments) 
          
已过时。 如果在保存属性列表时发生 I/O 错误,则此方法不抛出 IOException。保存属性列表的首选方法是通过 store(OutputStream out, String comments) 方法或 storeToXML(OutputStream os, String comment) 方法来进行。

 Object

setProperty(String key, String value) 
          
调用 Hashtable 的方法 put

 void

store(OutputStream out, String comments) 
          
以适合使用 load 方法加载到 Properties 表中的格式,将此 Properties 表中的属性列表(键和元素对)写入输出流。

 void

storeToXML(OutputStream os, String comment) 
          
发出一个表示此表中包含的所有属性的 XML 文档。

 void

storeToXML(OutputStream os, String comment, String encoding) 
          
使用指定的编码发出一个表示此表中包含的所有属性的 XML 文档。

 

import java.util.Properties;

import java.io.*;

public class PropertiesDemo{

    public static void main(String args[])throws Exception{

        //构建Properties工具对象

        Properties prop=new Properties();

        //加载属性文件

        prop.load(new FileInputStream(new File("d:\\src\\school.properties")));

        String name=prop.getProperty("name");

        String address=prop.getProperty("address");

        System.out.println(name);

        System.out.println(address);

    }

}

 

你可能感兴趣的:(java,IO,File,FileInputStream)