学习知识:输入流和输出流读文件的简单使用
test.txt:
iloveu是我爱你的意思。
Main.java
import java.io.*;public class Main {public static void main(String[] args) {// 1.利用输入流读文件//读取test.txt并输出文件内容try{FileInputStream inpt = new FileInputStream("D:\\LearnJAVA\\stream\\src\\test.txt");int b;System.out.println("利用FileInputStream.read()读文件(获取到的是字节流,有中文变成乱码的问题):");while((b = inpt.read())!=-1){ //read读取一个字符,返回为byteSystem.out.print((char)b); //利用强转,转为char输出}System.out.println();} catch (FileNotFoundException e) {throw new RuntimeException(e);} catch (IOException e) {throw new RuntimeException(e);} //FileInputStream等类有throws,要做好对应的异常捕获。// 2.利用输出流写文件//读取test.txt并输出到testCopy.txt中try{FileOutputStream wf = new FileOutputStream("D:\\LearnJAVA\\stream\\src\\testCopy.txt");FileInputStream inpt = new FileInputStream("D:\\LearnJAVA\\stream\\src\\test.txt");int c = -1; //存储读取的字节数byte[] b= new byte[512]; //缓冲字节数组,一次读到的字节会存进这个数组while ((c=inpt.read(b,0,512))!=-1){ //读取512字节的数据,存入b数组wf.write(b,0,c); //将b数组里读到的字节写入输出文件中}System.out.println("写文件完成");} catch (FileNotFoundException e) {throw new RuntimeException(e);} catch (IOException e) {throw new RuntimeException(e);}}
}
输出结果: