Java流基础、文件File和IO操作

Java的io几乎包含所有操作、输入输出所有的类,所有的这些类都代表了输入源和输出目标。
Java的io流包含了很多格式支持:基本类型、对象、本地化字符集等等。一个流可以理解为一个数据序列,输入流表示从一个源读取数据,输出流表示向一个目标写入数据。
Java给io提供了强大的支持,更为广泛的应用到网络编程中。本文就其基本使用给出概述。


一、读取控制台输入输出

Java的控制台由System.in构成。
为了获得一个绑定控制台的字符流,可以把System.in包装在一个BufferedReadered对象中创建一个字符流。
下面是其基本语法:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

BufferedReader 对象创建之后,可以利用read方法从控制台读取字符,或者readLine方法读取一个字符串。


二、从控制台读取多字符输入

从BufferedReader 对象读取一个字符需要使用read方法,语法如下:

int read() throws Exception

每次调用read方法,从输入流读取一个字符作为整数值返回,流结束返回-1,该方法抛出IOException异常。

public class BRRead {
    public static void main(String[] args) throws IOException {
        char c;
        // 使用 System.in 创建 BufferedReader
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("输入字符, 按下 'q' 键退出。");
        // 读取字符
        do {
            c = (char) br.read();
            System.out.println(c);
        } while (c != 'q');
    }
}

三、从控制台读取字符串

从标准输入读取一个字符串需要使用BufferedReader的readLine方法:

String readLine( ) throws IOException
public class BRReadLines {
    public static void main(String[] args) throws IOException {
        // 使用 System.in 创建 BufferedReader
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String str;
        System.out.println("Enter lines of text.");
        System.out.println("Enter 'end' to quit.");
        do {
            str = br.readLine();
            System.out.println(str);
        } while (!str.equals("end"));
    }
}

四、控制台输出

在此前已经介绍过,控制台的输出由 print( ) 和 println() 完成。这些方法都由类 PrintStream 定义,System.out 是该类对象的一个引用。
PrintStream 继承了 OutputStream类,并且实现了方法 write()。这样,write() 也可以用来往控制台写操作。
PrintStream定义write的最简单格式:

void write(int byteval)

该方法把byteal的低八位字节写入到流中。

public class WriteDemo {
    public static void main(String[] args) {
        int b;
        b = 'A';
        System.out.write(b);
        System.out.write('\n');
    }
}

五、读写文件

给出描述输入流和输出流的类层图:
在这里插入图片描述


六、FileInputStream

该流作用从文件读取数据,其对象可以用关键字new来创建。
多种构造方法实现创建对象。

InputStream f = new FileInputStream("C:/java/hello");

可以使用一个文件对象创建一个输入流对象来读取文件,首先使用File方法创建文件对象:

File f = new File("C:/java/hello");
InputStream in = new FileInputStream(f);

创建InputStream对象,可以使用下面的对象读取流或者进行其他流操作。
文件流方法


七、FileOutoutStream

该类创建以恶搞文件并且向文件内写入数据。
若该流在打开文件输出前,目标文件并不存在,那么该流回创建这个文件。
有两个构造方法可以实现创建FileOutPutStream对象。
使用字符串类型的文件名来创建一个输出流对象:

OutputStream f = new FileOutputStream("C:/java/hello")

也可以使用一个文件对象来创建一个输出流读写文件,使用File方法创建一个对象:

File f = new File("C:/java/hello");
OutputStream fOut = new FileOutputStream(f);

下面这个demo演示InputStream和OutputStream用法的例子:

public class fileStreamTest {
    public static void main(String[] args) {
        try {
            byte bWrite[] = { 11, 21, 3, 40, 5 };
            OutputStream os = new FileOutputStream("test.txt");
            for (int x = 0; x < bWrite.length; x++) {
                os.write(bWrite[x]); // writes the bytes
            }
            os.close();
 
            InputStream is = new FileInputStream("test.txt");
            int size = is.available();
 
            for (int i = 0; i < size; i++) {
                System.out.print((char) is.read() + "  ");
            }
            is.close();
        } catch (IOException e) {
            System.out.print("Exception");
        }
    }
}

该代码首先创建文件test.txt,然后把给定的数字以二进制形式写入文件,同时输出到控制台上,以上代码是由于二进制写入,存在乱码,用下述方法修改乱码问题:

public class fileStreamTest2 {
    public static void main(String[] args) throws IOException {
 
        File f = new File("a.txt");
        FileOutputStream fop = new FileOutputStream(f);
        // 构建FileOutputStream对象,文件不存在会自动新建
 
        OutputStreamWriter writer = new OutputStreamWriter(fop, "UTF-8");
        // 构建OutputStreamWriter对象,参数可以指定编码,默认为操作系统默认编码,windows上是gbk
 
        writer.append("中文输入");
        // 写入到缓冲区
 
        writer.append("\r\n");
        // 换行
 
        writer.append("English");
        // 刷新缓存冲,写入到文件,如果下面已经没有写入的内容了,直接close也会写入
 
        writer.close();
        // 关闭写入流,同时会把缓冲区内容写入文件,所以上面的注释掉
 
        fop.close();
        // 关闭输出流,释放系统资源
 
        FileInputStream fip = new FileInputStream(f);
        // 构建FileInputStream对象
 
        InputStreamReader reader = new InputStreamReader(fip, "UTF-8");
        // 构建InputStreamReader对象,编码与写入相同
 
        StringBuffer sb = new StringBuffer();
        while (reader.ready()) {
            sb.append((char) reader.read());
            // 转成char加到StringBuffer对象中
        }
        System.out.println(sb.toString());
        reader.close();
        // 关闭读取流
 
        fip.close();
        // 关闭输入流,释放系统资源
 
    }
}

八、文件和IO

请关注下面链接:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值