IO 流--头歌(educoder)实训作业题目及答案

Java高级特性 - IO流

第1关:什么是IO流

第2关:字节流-输入输出

package step2;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class Task {
	
	public void task() throws IOException{
		/********* Begin *********/
		File file = new File("src/step2/input/task.txt");
		FileInputStream fs = new FileInputStream(file);  
		byte[] b = new byte[8];                         
		fs.read(b);                                    
		String str = new String(b,"UTF-8");            
		System.out.println(str);
		File dir = new File("src/step2/output");
		if(!dir.exists()){
			dir.mkdir();
		}
		FileOutputStream out = new FileOutputStream("src/step2/output/output.txt"); 
		String str1 = "learning practice";
		byte[] c = str1.getBytes();   
		out.write(c);                
		out.flush();                 
		fs.close();					  
		out.close();
        
		
		/********* End *********/
	}
	
}

第3关:字符流 - 输入输出

package step3;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class Task {
	
	public void task() throws IOException{
		/********* Begin *********/
		String file1 = "src/step3/input/input.txt";
		FileReader fr = new FileReader(file1);
		char[] ch = new char[8];
		fr.read(ch);
		String file2 = "src/step3/output/output.txt";
		FileWriter fw = new FileWriter(file2);
		fw.write(ch);
		fr.close();
		fw.flush();
		fw.close();
				
		
		
		/********* End *********/		
	}
}

第4关:复制文件

package step4;

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

public class Task {
	
	public void task() throws IOException{
		/********* Begin *********/
		String file1 = "src/step4/input/input.txt";
		FileInputStream fr = new FileInputStream(file1);
		byte[] b = new byte[1024];
		int len = 0;
		String file2 = "src/step4/output/output.txt";
		FileOutputStream fw = new FileOutputStream(file2);
		while((len = fr.read(b))!=-1){
			fw.write(b,0,len);
		}
		fr.close();
		fw.close();
		String file3 = "src/step4/input/input.jpg";
		String file4 = "src/step4/output/output.jpg";
		FileInputStream fs = new FileInputStream(file3); 
		FileOutputStream fos = new FileOutputStream(file4);
		len = 0;       
		byte[] bys = new byte[1024];   
		while( (len = fs.read(bys)) != -1){
			fos.write(bys, 0, len);
		}
		
		fs.close();
		fos.close();
		
		/********* End *********/		
	}
}

猜你喜欢

转载自blog.csdn.net/qq_35353972/article/details/126960881