Java I/O流详解

一、流的概念和作用。

流是一种有顺序的,有起点和终点的字节集合,是对数据传输的总成或抽象。即数据在两设备之间的传输称之为流,流的本质是数据传输,根据数据传输的特性讲流抽象为各种类,方便更直观的进行数据操作。

二、IO流的分类。

根据数据处理类的不同分为:字符流和字节流。

根据数据流向不同分为:输入流和输出流。

三、字符流和字节流。

字符流的由来:因为数据编码的不同,而有了对字符进行高效操作的流对象,其本质就是基于字节流读取时,去查了指定的码表。字符流和字节流的区别:

(1)读写单位不同:字节流一字节(8bit)为单位,字符流以字符为单位,根据码表映射字符,一次可能读多个字节。

(2)处理对象不同:字节流能处理所有类型的数据(例如图片,avi),而字符流只能处理字符类型的数据。

(3)字节流操作的时候本身是不会用到缓冲区的,是对文件本身的直接操作。而字符流在操作的时候是会用到缓冲区的,通过缓冲区来操作文件。

结论:优先使用字节流,首先因为在硬盘上所有的文件都是以字节的形式进行传输或保存的,包括图片等内容。但是字符流只是在内存中才会形成,所以在开发中字节流使用广泛。

四、输入流和输出流。

对输入流只能进行读操作,对输出流只能进行写操作。程序中根据数据传输的不同特性使用不同的流。

五、输入字节流InputStream。

InputStream是所有输入字节流的父类,它是一个抽象类。

ByteArrayInputStream、StringBufferInputStream、FileInputStream 是三种基本的介质流,它们分别从Byte 数组、StringBuffer、和本地文件中读取数据。PipedInputStream 是从与其它线程共用的管道中读取数据,与Piped 相关的知识后续单独介绍。
ObjectInputStream 和所有FilterInputStream的子类都是装饰流(装饰器模式的主角)。意思是FileInputStream类可以通过一个String路径名创建一个对象,FileInputStream(String name)。而DataInputStream必须装饰一个类才能返回一个对象,DataInputStream(InputStream in)。
讲解Demo。

读取文件,节省空间。

/*

  • To change this license header, choose License Headers in Project Properties.
  • To change this template file, choose Tools | Templates
  • and open the template in the editor.
    */

package javaio;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**

  • 字节流读取文件内容

  • 节省空间的方式

  • @author xk
    */
    public class IoTest {

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

     String fileName = "D:"+File.separator+"hello.txt";
     File f = new File(fileName);
     InputStream in = new FileInputStream(f);
     byte[] b = new byte[(int)f.length()];
     in.read(b);
     System.err.println("长度为="+f.length());
     in.close();
     System.err.println(new String(b));
    

    }

}
逐一字节读:
/*

  • To change this license header, choose License Headers in Project Properties.
  • To change this template file, choose Tools | Templates
  • and open the template in the editor.
    */

package javaio;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**

  • 逐字节读

  • 读取文件内容,节省空间

  • @author xk
    */
    public class IoTest {

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

     String fileName = "D:"+File.separator+"hello.txt";
     File f = new File(fileName);
     InputStream in = new FileInputStream(f);
     byte[] b = new byte[(int)f.length()];
     for(int i = 0;i< b.length;i++){
         b[i] = (byte) in.read();
     }
     in.close();
     System.err.println(new String(b));
    

    }

}
注意:上面的几个例子都是在知道文件的内容多大,然后才展开的,有时候我们不知道文件有多大,这种情况下,我们需要判断是否独到文件的末尾。
/*

  • To change this license header, choose License Headers in Project Properties.
  • To change this template file, choose Tools | Templates
  • and open the template in the editor.
    */

package javaio;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**

  • 逐字节读取文件内容

  • @author xk
    */
    public class IoTest {

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

     String fileName = "D:"+File.separator+"hello.txt";
     File f = new File(fileName);
     InputStream in = new FileInputStream(f);
     byte[] b = new byte[1024];
     int count = 0;
     int temp = 0;
     while((temp = in.read())!=(-1)){
         b[count++] = (byte)temp;
     }
     in.close();
     System.err.println(new String(b));
    

    }

}
注意:当读到文件末尾的时候会返回-1.正常情况下是不会返回-1的。
PushBackInputStream回退流操作:

/*

  • To change this license header, choose License Headers in Project Properties.
  • To change this template file, choose Tools | Templates
  • and open the template in the editor.
    */
    package javaio;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.PushbackInputStream;

/**

  • @author xk
    */
    public class IoTest {

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

     String str = "hello,rollenholt";
     PushbackInputStream push = null;
     ByteArrayInputStream bat = null;
     bat = new ByteArrayInputStream(str.getBytes());
     push = new PushbackInputStream(bat);
     int temp = 0;
     while ((temp = push.read()) != -1) {
         if (temp == ',') {
             push.unread(temp);
             temp = push.read();
             System.out.print("(回退" + (char) temp + ") ");
         } else {
             System.out.print((char) temp);
         }
     }
    

    }
    }
    六、输出字节流OutputStream。
    OutputStream是所有输出流的父类,它是一个抽象类。

ByteArrayOutputStream、FileOutputStream是两种基本的介质流,它们分别向Byte 数组、和本地文件中写入数据。PipedOutputStream 是向与其它线程共用的管道中写入数据,
ObjectOutputStream 和所有FilterOutputStream的子类都是装饰流。具体例子跟InputStream是对应的。

实例Demo:

向文件中写入字符串:

/*

  • To change this license header, choose License Headers in Project Properties.
  • To change this template file, choose Tools | Templates
  • and open the template in the editor.
    */
    package javaio;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**

  • @author xk
    */
    public class OutputStreamDemo {

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

     String fileName = "D:" + File.separator + "hello.txt";
     File f = new File(fileName);
     OutputStream os = new FileOutputStream(f);
     String str = "xukuntest";
     byte[] b = str.getBytes();
     os.write(b);
     os.close();
    

    }
    }
    /**

  • 字节流

  • 向文件中一个字节一个字节的写入字符串

  • /
    import java.io.
    ;
    class hello{
    public static void main(String[] args) throws IOException {
    String fileName="D:"+File.separator+"hello.txt";
    File f=new File(fileName);
    OutputStream out =new FileOutputStream(f);
    String str="Hello World!!";
    byte[] b=str.getBytes();
    for (int i = 0; i < b.length; i++) {
    out.write(b[i]);
    }
    out.close();
    }
    }
    /**

  • 字节流

  • 向文件中追加新内容:

  • /
    import java.io.
    ;
    class hello{
    public static void main(String[] args) throws IOException {
    String fileName="D:"+File.separator+"hello.txt";
    File f=new File(fileName);
    OutputStream out =new FileOutputStream(f,true);//true表示追加模式,否则为覆盖
    String str="Rollen";
    //String str="\r\nRollen"; 可以换行
    byte[] b=str.getBytes();
    for (int i = 0; i < b.length; i++) {
    out.write(b[i]);
    }
    out.close();
    }
    }
    /**

  • 文件的复制

  • /
    import java.io.
    ;
    class hello{
    public static void main(String[] args) throws IOException {
    if(args.length!=2){
    System.out.println("命令行参数输入有误,请检查");
    System.exit(1);
    }
    File file1=new File(args[0]);
    File file2=new File(args[1]);

    if(!file1.exists()){
    System.out.println("被复制的文件不存在");
    System.exit(1);
    }
    InputStream input=new FileInputStream(file1);
    OutputStream output=new FileOutputStream(file2);
    if((input!=null)&&(output!=null)){
    int temp=0;
    while((temp=input.read())!=(-1)){
    output.write(temp);
    }
    }
    input.close();
    output.close();
    }
    }
    /**

  • 使用内存操作流将一个大写字母转化为小写字母

  • /
    import java.io.
    ;
    class hello{
    public static void main(String[] args) throws IOException {
    String str="ROLLENHOLT";
    ByteArrayInputStream input=new ByteArrayInputStream(str.getBytes());
    ByteArrayOutputStream output=new ByteArrayOutputStream();
    int temp=0;
    while((temp=input.read())!=-1){
    char ch=(char)temp;
    output.write(Character.toLowerCase(ch));
    }
    String outStr=output.toString();
    input.close();
    output.close();
    System.out.println(outStr);
    }
    }
    /**

  • 验证管道流

  • /
    import java.io.
    ;

/**

  • 消息发送类
  • */
    class Send implements Runnable{
    private PipedOutputStream out=null;
    public Send() {
    out=new PipedOutputStream();
    }
    public PipedOutputStream getOut(){
    return this.out;
    }
    public void run(){
    String message="hello , Rollen";
    try{
    out.write(message.getBytes());
    }catch (Exception e) {
    e.printStackTrace();
    }try{
    out.close();
    }catch (Exception e) {
    e.printStackTrace();
    }
    }
    }

/**

  • 接受消息类
  • /
    class Recive implements Runnable{
    private PipedInputStream input=null;
    public Recive(){
    this.input=new PipedInputStream();
    }
    public PipedInputStream getInput(){
    return this.input;
    }
    public void run(){
    byte[] b=new byte[1000];
    int len=0;
    try{
    len=this.input.read(b);
    }catch (Exception e) {
    e.printStackTrace();
    }try{
    input.close();
    }catch (Exception e) {
    e.printStackTrace();
    }
    System.out.println("接受的内容为 "+(new String(b,0,len)));
    }
    }
    /
    *
  • 测试类
  • */
    class hello{
    public static void main(String[] args) throws IOException {
    Send send=new Send();
    Recive recive=new Recive();
    try{
    //管道连接
    send.getOut().connect(recive.getInput());
    }catch (Exception e) {
    e.printStackTrace();
    }
    new Thread(send).start();
    new Thread(recive).start();
    }
    }
    DataOutputStream类示例
    import java.io.DataOutputStream;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    public class DataOutputStreamDemo{
    public static void main(String[] args) throws IOException{
    File file = new File("d:" + File.separator +"hello.txt");
    char[] ch = { 'A', 'B', 'C' };
    DataOutputStream out = null;
    out = new DataOutputStream(new FileOutputStream(file));
    for(char temp : ch){
    out.writeChar(temp);
    }
    out.close();
    }
    }
    java.util.zip.ZipOutputStream
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipOutputStream;

public class ZipOutputStreamDemo1{
public static void main(String[] args) throws IOException{
File file = new File("d:" + File.separator +"hello.txt");
File zipFile = new File("d:" + File.separator +"hello.zip");
InputStream input = new FileInputStream(file);
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(
zipFile));
zipOut.putNextEntry(new ZipEntry(file.getName()));
// 设置注释
zipOut.setComment("hello");
int temp = 0;
while((temp = input.read()) != -1){
zipOut.write(temp);
}
input.close();
zipOut.close();
}
}
【案例】ZipOutputStream类压缩多个文件
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**

  • 一次性压缩多个文件
  • */
    public class ZipOutputStreamDemo2{
    public static void main(String[] args) throws IOException{
    // 要被压缩的文件夹
    File file = new File("d:" + File.separator +"temp");
    File zipFile = new File("d:" + File.separator + "zipFile.zip");
    InputStream input = null;
    ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(
    zipFile));
    zipOut.setComment("hello");
    if(file.isDirectory()){
    File[] files = file.listFiles();
    for(int i = 0; i < files.length; ++i){
    input = newFileInputStream(files[i]);
    zipOut.putNextEntry(newZipEntry(file.getName()
    + File.separator +files[i].getName()));
    int temp = 0;
    while((temp = input.read()) !=-1){
    zipOut.write(temp);
    }
    input.close();
    }
    }
    zipOut.close();
    }
    }
    【案例】ZipFile类展示
    import java.io.File;
    import java.io.IOException;
    import java.util.zip.ZipFile;

/**
*ZipFile演示

  • */
    public class ZipFileDemo{
    public static void main(String[] args) throws IOException{
    File file = new File("d:" + File.separator +"hello.zip");
    ZipFile zipFile = new ZipFile(file);
    System.out.println("压缩文件的名称为:" + zipFile.getName());
    }
    }
    【案例】解压缩文件(压缩文件中只有一个文件的情况)
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipFile;

/**

  • 解压缩文件(压缩文件中只有一个文件的情况)
  • */
    public class ZipFileDemo2{
    public static void main(String[] args) throws IOException{
    File file = new File("d:" + File.separator +"hello.zip");
    File outFile = new File("d:" + File.separator +"unZipFile.txt");
    ZipFile zipFile = new ZipFile(file);
    ZipEntry entry =zipFile.getEntry("hello.txt");
    InputStream input = zipFile.getInputStream(entry);
    OutputStream output = new FileOutputStream(outFile);
    int temp = 0;
    while((temp = input.read()) != -1){
    output.write(temp);
    }
    input.close();
    output.close();
    }
    }
    【案例】ZipInputStream类解压缩一个压缩文件中包含多个文件的情况
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipFile;
    import java.util.zip.ZipInputStream;

/**

  • 解压缩一个压缩文件中包含多个文件的情况
  • */
    public class ZipFileDemo3{
    public static void main(String[] args) throws IOException{
    File file = new File("d:" +File.separator + "zipFile.zip");
    File outFile = null;
    ZipFile zipFile = new ZipFile(file);
    ZipInputStream zipInput = new ZipInputStream(new FileInputStream(file));
    ZipEntry entry = null;
    InputStream input = null;
    OutputStream output = null;
    while((entry = zipInput.getNextEntry()) != null){
    System.out.println("解压缩" + entry.getName() + "文件");
    outFile = new File("d:" + File.separator + entry.getName());
    if(!outFile.getParentFile().exists()){
    outFile.getParentFile().mkdir();
    }
    if(!outFile.exists()){
    outFile.createNewFile();
    }
    input = zipFile.getInputStream(entry);
    output = new FileOutputStream(outFile);
    int temp = 0;
    while((temp = input.read()) != -1){
    output.write(temp);
    }
    input.close();
    output.close();
    }
    }
    }
    七.几个特殊的输入流类分析
    LineNumberInputStream
    主要完成从流中读取数据时,会得到相应的行号,至于什么时候分行、在哪里分行是由改类主动确定的,并不是在原始中有这样一个行号。在输出部分没有对应的部分,我们完全可以自己建立一个LineNumberOutputStream,在最初写入时会有一个基准的行号,以后每次遇到换行时会在下一行添加一个行号,看起来也是可以的。好像更不入流了。
    PushbackInputStream
    其功能是查看最后一个字节,不满意就放入缓冲区。主要用在编译器的语法、词法分析部分。输出部分的BufferedOutputStream 几乎实现相近的功能。
    StringBufferInputStream
    已经被Deprecated,本身就不应该出现在InputStream部分,主要因为String 应该属于字符流的范围。已经被废弃了,当然输出部分也没有必要需要它了!还允许它存在只是为了保持版本的向下兼容而已。
    SequenceInputStream
    可以认为是一个工具类,将两个或者多个输入流当成一个输入流依次读取。完全可以从IO 包中去除,还完全不影响IO 包的结构,却让其更“纯洁”――纯洁的Decorator 模式。
    【案例】将两个文本文件合并为另外一个文本文件
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.io.SequenceInputStream;

/**

  • 将两个文本文件合并为另外一个文本文件
  • /
    public class SequenceInputStreamDemo{
    public static voidmain(String[] args) throws IOException{
    File file1 = newFile("d:" + File.separator + "hello1.txt");
    File file2 = newFile("d:" + File.separator + "hello2.txt");
    File file3 = newFile("d:" + File.separator + "hello.txt");
    InputStream input1 =new FileInputStream(file1);
    InputStream input2 =new FileInputStream(file2);
    OutputStream output =new FileOutputStream(file3);
    // 合并流
    SequenceInputStreamsis = new SequenceInputStream(input1, input2);
    int temp = 0;
    while((temp =sis.read()) != -1){
    output.write(temp);
    }
    input1.close();
    input2.close();
    output.close();
    sis.close();
    }
    }
    PrintStream
    也可以认为是一个辅助工具。主要可以向其他输出流,或者FileInputStream 写入数据,本身内部实现还是带缓冲的。本质上是对其它流的综合运用的一个工具而已。一样可以踢出IO 包!System.err和System.out 就是PrintStream 的实例!
    【案例】使用PrintStream进行格式化输出
    /
    *
  • 使用PrintStream进行输出
  • 并进行格式化
  • /
    import java.io.
    ;
    class hello {
    public static void main(String[] args) throws IOException {
    PrintStream print = new PrintStream(new FileOutputStream(newFile("d:"
    + File.separator +"hello.txt")));
    String name="Rollen";
    int age=20;
    print.printf("姓名:%s. 年龄:%d.",name,age);
    print.close();
    }
    }
    【案例】使用OutputStream向屏幕上输出内容
    /**
  • 使用OutputStream向屏幕上输出内容
  • /
    import java.io.
    ;
    class hello {
    public static void main(String[] args) throws IOException {
    OutputStream out=System.out;
    try{
    out.write("hello".getBytes());
    }catch (Exception e) {
    e.printStackTrace();
    }
    try{
    out.close();
    }catch (Exception e) {
    e.printStackTrace();
    }
    }
    }
    【案例】输入输出重定向
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.PrintStream;

/**

  • 为System.out.println()重定向输出
  • /
    public class systemDemo{
    public static void main(String[] args){
    // 此刻直接输出到屏幕
    System.out.println("hello");
    File file = new File("d:" + File.separator +"hello.txt");
    try{
    System.setOut(new PrintStream(new FileOutputStream(file)));
    }catch(FileNotFoundException e){
    e.printStackTrace();
    }
    System.out.println("这些内容在文件中才能看到哦!");
    }
    【案例】System.in重定向
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    /
    *
    *System.in重定向
  • /
    public class systemIn{
    public static void main(String[] args){
    File file = new File("d:" + File.separator +"hello.txt");
    if(!file.exists()){
    return;
    }else{
    try{
    System.setIn(newFileInputStream(file));
    }catch(FileNotFoundException e){
    e.printStackTrace();
    }
    byte[] bytes = new byte[1024];
    int len = 0;
    try{
    len = System.in.read(bytes);
    }catch(IOException e){
    e.printStackTrace();
    }
    System.out.println("读入的内容为:" + new String(bytes, 0, len));
    }
    }
    }
    八.字符输入流Reader
    定义和说明:
    在上面的继承关系图中可以看出:
    Reader 是所有的输入字符流的父类,它是一个抽象类。
    CharReader、StringReader是两种基本的介质流,它们分别将Char 数组、String中读取数据。PipedReader 是从与其它线程共用的管道中读取数据。
    BufferedReader 很明显就是一个装饰器,它和其子类负责装饰其它Reader 对象。
    FilterReader 是所有自定义具体装饰流的父类,其子类PushbackReader 对Reader 对象进行装饰,会增加一个行号。
    InputStreamReader 是一个连接字节流和字符流的桥梁,它将字节流转变为字符流。FileReader可以说是一个达到此功能、常用的工具类,在其源代码中明显使用了将FileInputStream 转变为Reader 的方法。我们可以从这个类中得到一定的技巧。Reader 中各个类的用途和使用方法基本和InputStream 中的类使用一致。后面会有Reader 与InputStream 的对应关系。
    【案例】以循环方式从文件中读取内容
    /
    *
  • 字符流
  • 从文件中读出内容
  • /
    import java.io.
    ;
    class hello{
    public static void main(String[] args) throws IOException {
    String fileName="D:"+File.separator+"hello.txt";
    File f=new File(fileName);
    char[] ch=new char[100];
    Reader read=new FileReader(f);
    int temp=0;
    int count=0;
    while((temp=read.read())!=(-1)){
    ch[count++]=(char)temp;
    }
    read.close();
    System.out.println("内容为"+new String(ch,0,count));
    }
    }
    【案例】BufferedReader的小例子
    注意:BufferedReader只能接受字符流的缓冲区,因为每一个中文需要占据两个字节,所以需要将System.in这个字节输入流变为字符输入流,采用:
    BufferedReader buf = new BufferedReader(newInputStreamReader(System.in));
    下面是一个实例:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**

  • 使用缓冲区从键盘上读入内容
  • */
    public class BufferedReaderDemo{
    public static void main(String[] args){
    BufferedReader buf = new BufferedReader(
    newInputStreamReader(System.in));
    String str = null;
    System.out.println("请输入内容");
    try{
    str = buf.readLine();
    }catch(IOException e){
    e.printStackTrace();
    }
    System.out.println("你输入的内容是:" + str);
    }
    }
    【案例】Scanner类从文件中读出内容
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.Scanner;

/**
*Scanner的小例子,从文件中读内容

  • */
    public class ScannerDemo{
    public static void main(String[] args){

    File file = new File("d:" + File.separator +"hello.txt");
    Scanner sca = null;
    try{
    sca = new Scanner(file);
    }catch(FileNotFoundException e){
    e.printStackTrace();
    }
    String str = sca.next();
    System.out.println("从文件中读取的内容是:" + str);
    }
    }
    九.字符输出流Writer
    定义和说明:
    在上面的关系图中可以看出:
    Writer 是所有的输出字符流的父类,它是一个抽象类。
    CharArrayWriter、StringWriter 是两种基本的介质流,它们分别向Char 数组、String 中写入数据。
    PipedWriter 是向与其它线程共用的管道中写入数据,
    BufferedWriter 是一个装饰器为Writer 提供缓冲功能。
    PrintWriter 和PrintStream 极其类似,功能和使用也非常相似。
    OutputStreamWriter 是OutputStream 到Writer 转换的桥梁,它的子类FileWriter 其实就是一个实现此功能的具体类(具体可以研究一SourceCode)。功能和使用和OutputStream 极其类似,后面会有它们的对应图。
    实例操作演示:
    【案例】向文件中写入数据
    /**

  • 字符流

  • 写入数据

  • /
    import java.io.
    ;
    class hello{
    public static void main(String[] args) throws IOException {
    String fileName="D:"+File.separator+"hello.txt";
    File f=new File(fileName);
    Writer out =new FileWriter(f);
    String str="hello";
    out.write(str);
    out.close();
    }
    }
    注意:这个例子上之前的例子没什么区别,只是你可以直接输入字符串,而不需要你将字符串转化为字节数组。当你如果想问文件中追加内容的时候,可以使用将上面的声明out的哪一行换为:
    Writer out =new FileWriter(f,true);
    这样,当你运行程序的时候,会发现文件内容变为:hellohello如果想在文件中换行的话,需要使用“\r\n”比如将str变为String str="\r\nhello";这样文件追加的str的内容就会换行了。
    十.字符流与字节流转换
    转换流的特点:
    (1)其是字符流和字节流之间的桥梁
    (2)可对读取到的字节数据经过指定编码转换成字符
    (3)可对读取到的字符数据经过指定编码转换成字节
    何时使用转换流?
    当字节和字符之间有转换动作时;
    流操作的数据需要编码或解码时。
    具体的对象体现:
    InputStreamReader:字节到字符的桥梁
    OutputStreamWriter:字符到字节的桥梁
    这两个流对象是字符体系中的成员,它们有转换作用,本身又是字符流,所以在构造的时候需要传入字节流对象进来。
    字节流和字符流转换实例:
    【案例】将字节输出流转化为字符输出流
    /**

  • 将字节输出流转化为字符输出流

  • /
    import java.io.
    ;
    class hello{
    public static void main(String[] args) throws IOException {
    String fileName= "d:"+File.separator+"hello.txt";
    File file=new File(fileName);
    Writer out=new OutputStreamWriter(new FileOutputStream(file));
    out.write("hello");
    out.close();
    }
    }
    【案例】将字节输入流转换为字符输入流
    /**

  • 将字节输入流变为字符输入流

  • /
    import java.io.
    ;
    class hello{
    public static void main(String[] args) throws IOException {
    String fileName= "d:"+File.separator+"hello.txt";
    File file=new File(fileName);
    Reader read=new InputStreamReader(new FileInputStream(file));
    char[] b=new char[100];
    int len=read.read(b);
    System.out.println(new String(b,0,len));
    read.close();
    }
    }
    十一.File类
    File类是对文件系统中文件以及文件夹进行封装的对象,可以通过对象的思想来操作文件和文件夹。 File类保存文件或目录的各种元数据信息,包括文件名、文件长度、最后修改时间、是否可读、获取当前文件的路径名,判断指定文件是否存在、获得当前目录中的文件列表,创建、删除文件和目录等方法。
    【案例 】创建一个文件
    import java.io.;
    class hello{
    public static void main(String[] args) {
    File f=new File("D:\hello.txt");
    try{
    f.createNewFile();
    }catch (Exception e) {
    e.printStackTrace();
    }
    }
    }
    【案例2】File类的两个常量
    import java.io.
    ;
    class hello{
    public static void main(String[] args) {
    System.out.println(File.separator);
    System.out.println(File.pathSeparator);
    }
    }
    此处多说几句:有些同学可能认为,我直接在windows下使用\进行分割不行吗?当然是可以的。但是在linux下就不是\了。所以,要想使得我们的代码跨平台,更加健壮,所以,大家都采用这两个常量吧,其实也多写不了几行。
    【案例3】File类中的常量改写案例1的代码:

import java.io.;
class hello{
public static void main(String[] args) {
String fileName="D:"+File.separator+"hello.txt";
File f=new File(fileName);
try{
f.createNewFile();
}catch (Exception e) {
e.printStackTrace();
}
}
}
【案例4】删除一个文件(或者文件夹)
import java.io.
;
class hello{
public static void main(String[] args) {
String fileName="D:"+File.separator+"hello.txt";
File f=new File(fileName);
if(f.exists()){
f.delete();
}else{
System.out.println("文件不存在");
}

}
}
【案例5】创建一个文件夹
/**

  • 创建一个文件夹
  • /
    import java.io.
    ;
    class hello{
    public static void main(String[] args) {
    String fileName="D:"+File.separator+"hello";
    File f=new File(fileName);
    f.mkdir();
    }
    }
    【案例6】列出目录下的所有文件
    /**
  • 使用list列出指定目录的全部文件
  • /
    import java.io.
    ;
    class hello{
    public static void main(String[] args) {
    String fileName="D:"+File.separator;
    File f=new File(fileName);
    String[] str=f.list();
    for (int i = 0; i < str.length; i++) {
    System.out.println(str[i]);
    }
    }
    }

转自:http://blog.csdn.net/u012815721/article/details/25279613

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,015评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,262评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,727评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,986评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,363评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,610评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,871评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,582评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,297评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,551评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,053评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,385评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,035评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,079评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,841评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,648评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,550评论 2 270

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,100评论 18 139
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,293评论 18 399
  • ¥开启¥ 【iAPP实现进入界面执行逐一显】 〖2017-08-25 15:22:14〗 《//首先开一个线程,因...
    小菜c阅读 6,204评论 0 17
  • 昨天,一朋友的电话把我从梦里拉醒。 他说:我好痛苦睡不着啊,我这人怎么总是擅长于失去一些重要的东西。 我不解:失去...
    非谓语阅读 622评论 0 2
  • 1.查询等待时间缩短数秒: 之前几秒现在几秒 做了哪些方面的优化? 答:之前少则5秒多则10秒以上,现在一般情况下...
    小公子阅读 266评论 0 0