Java IO全解

来源:互联网 发布:阿里云飞天有几个部门 编辑:程序博客网 时间:2024/06/04 23:22

JavaIO操作主要指使用Java进行输入输出操作,所有操作类都在java.io包中,其中最重要的就是5个类和一个接口,5个类指File、OutputStream、InputStream、Write、Reader;一个接口指serializable。

1、File类

唯一与文件本身有关的类,可以进行创建或删除文件等操作。
构造方法:

public File(String pathname)

要使用一个File类,需要向构造方法中传递一个文件路径,例如:“c:\demo.txt”。
其中常用的方法和常量:

public static final String pathSeparator //分隔符“;”public static final String separator //分隔符“\”public boolean createNewFile() throws IOException //创建文件public boolean delete()//删除文件public boolean exists()//判断文件存在否public boolean isDirectory()//判断是不是目录public long length()//返回文件大小public String[] list()//列出指定目录的全部内容的名称public File[] listFiles()//列出指定目录的全部内容public boolean mkdir()//创建一个目录public boolean renameTo()//重命名

2、字节流

程序需要数据时要使用输入流读取数据,当程序需要将数据保存起来时,就要使用输出流。主要由OutputStream类和InputStream类完成。
1、字节输出流:OutputStream
OutputStream是整个IO包中字节输出流的最大父类,因为是抽象类,必须用子类实例化,比如FileOutputStream。
常用方法:

public void write(byte b[]) throws IOException//将一个byte数组写入数据流public void write(byte b[], int off, int len)//将一个指定范围的byte数组写入数据流public abstract void write(int b)//将一个字节数据写入数据流public void close() throws IOException//关闭输出流public void flush() throws IOException//刷新缓冲区

2、向文件中写入字符串

public static void main(String[] args) throws Exception{        File file = new File("d:\\demo.txt");        OutputStream out = new FileOutputStream(file);        String s = "Hello World";        byte b[] = s.getBytes();        out.write(b);        out.close();    }

这里是把字符串变为byte数组,然后将数组直接写入文件,我们也可以通过循环把字节一个个写入到文件。

public static void main(String[] args) throws Exception{        File file = new File("d:\\demo.txt");        OutputStream out = new FileOutputStream(file);        String s = "Hello World";        byte b[] = s.getBytes();        //out.write(b);        for (int i=0;i<b.length;i++) {            out.write(i);        }        out.close();    }

3、字节输入流InputStream
可以通过InputStream从文件中把内容读取出来,因为是抽象类,必须用子类实例化。

public int available() throws IOException//可以取得输入文件的大小public void close() throws IOException//关闭输入流public abstract int read() throws IOException//读取内容,以数字的方式读取public int read(byte b[]) throws IOException//将内容读到byte数组中,同时返回读入的个数

4、从文件中读取内容

public static void main(String[] args) throws Exception{        File file = new File("d:\\demo.txt");        InputStream input = new FileInputStream(file);        byte b[] = new byte[1024];        input.read(b);        input.close();        System.out.println(new String(b));    }

由于我们的数组过大,而实际内容只有11字节,所以在数组变字符串的时候后面有很多空格。为了解决这个问题,我们可以改一下程序,因为read方法会返回向数组中读入了多少数据,改成这样:

 public static void main(String[] args) throws Exception{        File file = new File("d:\\demo.txt");        InputStream input = new FileInputStream(file);        byte b[] = new byte[1024];        int len = input.read(b);        input.close();        System.out.println(new String(b,0,len));    }

上面代码是从输出字符串改的,我们更好的办法其实是从读取的时候进行更改:

public static void main(String[] args) throws Exception{        File file = new File("d:\\demo.txt");        InputStream input = new FileInputStream(file);        byte b[] = new byte[(int)file.length()];        input.read(b);        input.close();        System.out.println(new String(b));    }

同样,也可以循环读取:

public static void main(String[] args) throws Exception{        File file = new File("d:\\demo.txt");        InputStream input = new FileInputStream(file);        byte b[] = new byte[(int)file.length()];        for (int i=0;i<b.length;i++) {            b[i]=(byte)input.read();        }        input.close();        System.out.println(new String(b));    }

但是,以上的程序是在明确知道了具体数组大小前提下开展的,如果不知道大小,只能通过判断是否读到文件末尾来读文件。

3、字符流

java中一个字符等于两个字节,提供了Reader和writer两个专门操作字符流的类。
1、字符输出流Writer

public static void main(String[] args) throws Exception{        File file = new File("d:\\demo2.txt");        Writer out = new FileWriter(file);        String s = "hello world";        out.write(s);        out.close();    }

过程和OutputStream的操作流程没有太大区别,好处是可以直接输出字符串,不用将字符串变成byte数组再输出。
2、字符输入流Reader

public static void main(String[] args) throws Exception{        File file = new File("d:\\demo2.txt");        Reader reader = new FileReader(file);        char b[] = new char[1024];        int len = reader.read(b);        reader.close();        System.out.println(new String(b,0,len));    }

循环输入

public static void main(String[] args) throws Exception{        File file = new File("d:\\demo2.txt");        Reader reader = new FileReader(file);        int len = 0;        char b[] = new char[1024];        int temp = 0;        while ((temp=reader.read())!=-1){            b[len] = (char) temp;            len++;        }        reader.close();        System.out.println(new String(b,0,len));    }

4、字符流和字节流区别

字节流在操作时不会用到缓冲区(内存),是文件本身直接操作,而字符流在操作是使用了缓冲区,通过缓冲区再操作文件。如果想在不关闭字符流的情况也强制输出内容,可以用Writer的flush()方法。

5、转换流

OutputStreamWriter:是Writer子类,将输出的字符流变成字节流,即将一个字符流的输出对象变成字节流的输出对象。
InputStreamReader:是Reader子类,将输入的字节流变成字符流,即将一个字节流的输入对象变成字符流的输入对象。
字节输出流变成字符输出流:

public static void main(String[] args) throws Exception{        File file = new File("d:\\demo2.txt");        //字节流变成字符流        Writer out = new OutputStreamWriter(new FileOutputStream(file));        out.write("hello world");        out.close();    }

字节输入流变成字符输入流:

public static void main(String[] args) throws Exception{        File file = new File("d:\\demo2.txt");        //字节流变成字符流        Reader input = new InputStreamReader(new FileInputStream(file));        char c[] = new char[1024];        int len = input.read(c);        input.close();        System.out.println(new String(c,0,len));    }

6、内存操作流

前面的输出和输入都是从文件中来的,我们也可以将输入和输出的位置设置在内存上。此时要用ByteArrayInputStream和ByteArrayOutputStream。
ByteArrayInputStream主要是将内容写到内存中,ByteArrayOutputStream是将内存中的数据输出,也就是把内存中的数据取出。

public ByteArrayInputStream(byte buf[])//将内容全部写入内存public ByteArrayInputStream(byte buf[], int offset, int length)//指定范围的内容写到内存
public ByteArrayOutputStream()//创建对象public synchronized void write(int b)//将内容从内存中输出

内存操作流一般在生成临时信息时才会使用,避免生成文件,然后还得删除文件这样的繁琐操作,而是直接在内存中完成。

7、管道流

管道流作用是可以进行两个线程间的通信,分为管道输出流PipedOutputStream和PipedInputStream。如果要进行管道输出,必须把输出流连在输入流上,在PipedOutputStream上有如下方法连接管道:

public synchronized void connect(PipedInputStream snk) throws IOException

8、BufferedReader

BufferedReader类用于从缓冲区中读取内容。

public BufferedReader(Reader in)//接收一个Reader类实例public String readLine() throws IOException//一次性从缓冲区中将内容全部读取出来

由构造方法可知,只能接受字符输入流。
键盘输入数据:

 public static void main(String[] args) throws Exception{        BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));        String str = null;        System.out.println("请输入内容");        str = buf.readLine();        System.out.println("内容:"+str);    }

9、Scanner类

public Scanner(File source) throws FileNotFoundExceptionpublic Scanner(InputStream source)public String next()//接收内容
原创粉丝点击