(使用字节流实现:FileInputStream和ByteArrayOutputStream)

来源:互联网 发布:mac风扇一直响 编辑:程序博客网 时间:2024/06/04 18:04

题目:在文本文件中存有斐波那契数列,1,1,2,3,5,8,13,21,34,55,……,读取第12个数(使用字节流实现:FileInputStream和ByteArrayOutputStream)
package 输入输出流;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;

public class Stream {

public static void main(String[] args) throws IOException {    try {        File file = new File("E:\\abc.txt");        InputStream inputStream = new FileInputStream(file);        BufferedInputStream bis = new BufferedInputStream(inputStream);        ByteArrayOutputStream bos = new ByteArrayOutputStream();        int date = -1;        while ((date = bis.read()) != -1) {            bos.write(date);        }        byte[] bytes = bos.toByteArray();        String content = new String(bytes);        System.out.println("content:" + content);        String[] split = content.split(",");        System.out.println("请输入要读取的位置:");        @SuppressWarnings("resource")        Scanner scanner = new Scanner(System.in);        int index = scanner.nextInt();        System.out.println("斐波那契数列的第" + index + "位置的数为:" + split[index - 1]);        bis.close();        inputStream.close();        bos.close();    } catch (FileNotFoundException e) {        e.printStackTrace();    } catch (IOException e) {        e.printStackTrace();    }}

}

阅读全文
0 0
原创粉丝点击