第1关:什么是IO流
第2关:字节流-输入输出
编程要求:
请仔细阅读右侧代码,根据方法内的提示,在Begin - End
区域内进行代码补充,具体任务如下:
- 读取
src/step2/input/
目录下的task.txt
文件信息并输出到控制台,使用Java代码将字符串learning practice
写入到src/step2/output/
目录下的output.txt
,若文件目录不存在,则创建该目录。
注意:临时字节数组需要定义长度为8
位,否则会有空格。
代码:
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;
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"); //通过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关:字符流 - 输入输出
编程要求:
请仔细阅读右侧代码,根据方法内的提示,在Begin - End
区域内进行代码补充,具体任务如下:
-
将
src/step3/input/
目录下的input.txt
文件复制到src/step3/output/
目录下; -
复制的新文件命名为
output.txt
; -
input.txt
文件中只有8
个字符。
代码:
package step3;
import java.io.*;
class Task {
public void task() throws IOException{
/********* Begin *********/
FileInputStream fis = new FileInputStream("src/step3/input/input.txt");
File file = new File("src/step3/output","output.txt");
FileOutputStream fos = new FileOutputStream(file);
byte[] bytes = new byte[8];
fis.read(bytes);
fos.write(bytes);
fos.close();
fis.close();
/********* End *********/
}
}
第4关:复制文件
编程要求
请仔细阅读右侧代码,根据方法内的提示,在Begin - End
区域内进行代码补充,具体任务如下:
-
复制
src/step4/input/
目录下的input.txt
文件到src/step4/output/
目录下,新文件命名为output.txt
; -
复制
src/step4/input/
目录下的input.jpg
文件到src/step4/output/
目录下,新文件命名为output.jpg
。
代码:
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 *********/
}
}