IO流的输入输出流案例

package day20200817;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class Demo07 {
    
    
	public static void main(String[] args) throws IOException {
    
    
		
		//1,编写一个程序,读取文件a.txt的内容并在控制台输出。如果源文件不存在,则显示相应的错误信息。
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try {
    
    
			 fis = new FileInputStream("a.txt");
		} catch (FileNotFoundException e) {
    
    
			// TODO Auto-generated catch block
			System.out.println("源文件没有找到");
			e.printStackTrace();
		}
		int i=0;
		while((i=fis.read())!=-1){
    
    
		
			System.out.print((char) i);
		}
		

	}
}
package day20200817;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Demo08 {
    
    
	//2,编写一个程序实现如下功能,从当前目录下的文件a.txt中读取80个字节
	//(实际读到的字节数可能比80少)并将读来的字节写入当前目录下的文件b.txt中
	public static void main(String[] args) throws IOException {
    
    
		FileInputStream fis = new FileInputStream("a.txt");
		FileOutputStream fos = new FileOutputStream("b.txt");
		byte[] b1 = new byte[80];
		int i=0;
		while((i=fis.read(b1))!=-1){
    
    
			fos.write(b1, 0, i);
		}
		fis.close();
		fos.close();
		
	}

}

package day20200817;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;

public class Demo09 {
    
    
	public static void main(String[] args) throws IOException {
    
    
	//3,使用java的输入/输出流技术将一个文本文件的内容按行
	//读出,每读出一行就顺序添加行号,并写入到另一个文件中。	
		BufferedReader br = new BufferedReader(new FileReader("a.txt"));
		BufferedWriter bw = new BufferedWriter(new FileWriter("b.txt"));
		String s = null;
		int i=1;
		while((s=br.readLine() )!= null){
    
    
			System.out.println(s);
			bw.write(i+":"+s);
			bw.newLine();
			i++;
		}
		bw.close();
		
		
		
		
		
		
		
	}

}

Guess you like

Origin blog.csdn.net/qq_43472248/article/details/108064176