IO文件的读取,以及写入文件内容

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

IO⽂件的读取,以及写⼊⽂件内容package zxc;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class IO {
public static void main(String[] args) {
IO a = new IO();
//设置读取路径
String filePath = "F:/abc.txt";
//调⽤读取⽅法
String input = a.readeFile(filePath);
//打印abc.txt⽂件的内容
System.out.println(input);
//写⼊到⽂件⾥的内容
String content = "今天2018/03/20,星期⼆";
//调⽤写⼊⽅法
a.writeFile(filePath,content);
//在修改⽂件内容后,再调⽤读取⽅法
String b = a.readeFile(filePath);
////打印修改后的abc.txt⽂件的内容
System.out.println(b);
}
/**
* FileInputStream类的使⽤:读取⽂件内容
* @param filePath
* @return
*/
private String readeFile(String filePath) {
FileInputStream input = null;
String result = "";
try {
//1.根据path实例化⼀个输⼊流的对象
input = new FileInputStream(filePath);
//2.返回这个输⼊流中可以被读的剩下的bytes字节的估计值;
int size = input.available();
//3.根据输⼊流的字节创建⼀个byte数组
byte[] array = new byte[size];
//4.把数据读取到byte数组中
input.read(array);
//5.根据获取的byte数组新建⼀个字符串,然后输出
result = new String(array);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(input != null){
try {
//关闭
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
/**
* FileOutputStream类的使⽤:内容写⼊到⽂件中
* @param filePath
* @return
*/
private void writeFile(String filePath,String content) {
FileOutputStream out = null;
try {
//1.根据路径创建输出流对象
out = new FileOutputStream(filePath) ;
//2.把String字符串转换成byte数组;
byte[] b = content.getBytes();
//3.把byte数组输出
out.write(b);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
F:/abc.txt ⽂件修改前的内容
执⾏后,控制台打印的内容
F:/abc.txt ⽂件修改后的内容
注意:
1. 在实际的项⽬中,所有的IO操作都应该放到⼦线程中操作,避免堵住主线程。

2. FileInputStream在读取⽂件内容的时候,我们传⼊⽂件的路径("F:/abcz.txt"), 如果这个路径下的⽂件不存在,那么在执⾏readFile()⽅法时
会报FileNotFoundException异常。

3. FileOutputStream在写⼊⽂件的时候,我们传⼊⽂件的路径("F:/abcz.txt"), 如果这个路径下的⽂件不存在,那么在执⾏writeFile()⽅法时, 会
默认给我们创建⼀个新的⽂件。

还有重要的⼀点,不会报异常。

执⾏之后:。

相关文档
最新文档