任务描述
本关任务:使用输入输出流读写文件。
相关知识
为了完成本关任务,你需要掌握:
1.如何使用输入流;
2.如何使用输出流。
输入流
我们通过一个示例,来看看输入流应该如何使用,首先我们在D
盘下创建一个hello.txt
文件。输入文本Hello Java Hello InputStream
。
在main
方法中加入如下代码:
输出:

Hello Java Hello InputStream
代码解释:
这个例子我们主要目的是,读取文件中的数据并将数据显示在控制台。
实现步骤是:首先读取文件转换成文件输入流(FileInputStream
),然后定义一个字节数组作为容器用来存储即将读取到的数据。fs.read(b)
函数的作用是将数据读取到b
数组中,最后通过编码表,将字节数组编码成字符。
输出流
我们使用输出流将字符串hello educoder
写入到一个文件中:
运行这段代码,打开D
盘下你会发现test.txt
文件被创建了,并且文件的内容是hello educoder
。
代码解释:
最佳实践
上面作为示例的两段代码都是存在很大问题的,什么问题呢?
因为在Java中对于流的操作是非常消耗资源的,如果我们使用流对一个资源进行操作了之后却没有释放它的资源,这就会造成系统资源的浪费,如果积累了很多这种空置的资源,最后可能会导致系统崩溃。
上述代码的最佳实践为:
OutputStream out = null;
try {
String file = "D://test.txt";
out = new FileOutputStream(file);
String str = "hello educoder";
byte[] b = str.getBytes();
out.write(b);
out.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close(); // 释放该输出流
} catch (IOException e) {
e.printStackTrace();
}
}
}
核心就是在使用完流之后,释放它所占用的资源。
编程要求
请仔细阅读右侧代码,根据方法内的提示,在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;
public class Task {
public void task() throws IOException{
/********* Begin *********/
File file = new File("src/step2/input/task.txt");
FileInputStream fs = new FileInputStream(file);
byte [] byte1 = new byte[8];
fs.read(byte1);
String str = new String(byte1,"UTF-8");
System.out.println(str);
File file1 = new File("src/step2/output");
File file2 = new File("src/step2/output/output.txt");
if(file1.exists()){
if(file2.exists()){
show(file2);
}else{
file2.createNewFile();
show(file2);
}
}else{
file1.mkdir();
file2.createNewFile();
show(file2);
}
/********* End *********/
}
public void show(File file) throws IOException{
FileOutputStream out = new FileOutputStream(file);
try{
String str = "learning practice";
byte [] byte2 = str.getBytes();
out.write(byte2);
out.flush();
}catch(Exception e){
e.printStackTrace();
}finally {
if (out != null) {
try {
out.close(); // 释放该输出流
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}