Java学习总结9

课堂小作业:将奇数位的字母大写输出!

实验代码:

package file;
import java.io.*;
public class filetext {
    public static void main(String[] args) throws Exception {
        File f = new File("D:\text");
        InputStream out = new FileInputStream(f);
        byte a[] = new byte[(int) f.length()];
        for (int i = 0; i < a.length; i++) {
            a[i] = (byte) out.read();
            if (i % 2 == 0) {
                a[i] = (byte) (a[i] - 32);
            }
        }
        out.close();
            System.out.print(new String(a));
    }
}

文件内容:

实验结果:

学习总结:

1、在java.io 包中,操作文件内容的主要有两大类:字节流、字符流。两类都分为输入和输出操作。字节流输出数据主要是使用OutputStream完成,输入使用InputStream完成;字符流输出数据主要是使用Writer类完成,输出数据使用Reader类完成。
操作流程为:
1)使用File类打开一个文件(电脑中能找到该文件)
2)通过字节流或字符流的子类,指定输出的位置
3)进行读/写操作
4)关闭输入/输出流

注意:使用File类时注意分隔符问题;上面四个类都是抽象类;IO操作属于资源操作,对于资源操作,操作完后必须关闭,否则可能会出现未知的错误。
2、追加内容: FileOutputStream(File file, boolean append) 换行:
3、常用方法:available() close() read() read(byte[]b) write() flush()
4、字节流在操作的时候本身不用缓存区的,是与文件直接对接的;而字符流操作时需要缓冲区。
5、InputStreamReader 是字节流通向字符流的桥梁
BufferedReader in= new BufferedReader(new InputStreamReader(System.in));

OutputStreamWriter 是字符流通向字节流的桥梁
Writer out= new BufferedWriter(new OutputStreamWriter(System.out))

原文地址:https://www.cnblogs.com/94ha-xc/p/11787735.html