您的位置:首页 > 编程语言 > PHP开发

【File】文件输入/输出。FileInputStream/FileOutputStream类

2017-08-02 20:33 190 查看

一、概述

FileInputStream类和FileOutputStream类都是用来操作磁盘文件。如果文件读取需求比较简单,可以使用FileInputStream(继承InputStream);同理FileOutputStream继承了OutputStream;

二、构造方法

FileInputStream(String name);

FileInputStream(File file);

三、源代码

下面请看实例(这个例子很经典):

package test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
* Created by Administrator on 2017/8/2 0002.
*/
public class FileOutputStreamTest {
public static void main(String[] args) {
File file = new File("word.txt");
try{
//创建FileOutputStream对象;
FileOutputStream out = new FileOutputStream(file);//把file文件打散,拆成流的形式;
//创建一个byte数组;
byte b[] = "Hello world".getBytes();//把字符串变成字节数组;
out.write(b);//流实例对象开始以字节流的方式把字节写入文件,这里注意,我们是站在byte b 的立场来看的,所以是写出,而不是写入;
out.close();//关闭流;
}catch(Exception e){
e.printStackTrace();
}
try{
FileInputStream in= new FileInputStream(file);//创建一个写入流,用来把file中的内容写出来;
byte byt [] = new byte[1024];//创建一个byte数组,用来把打散file的流变成byte过滤;
int len = in.read(byt);//流的实体通过byte形式来读取file中的内容
System.out.println("文件中的信息是:"+new String(byt,0,len));
in.close();//关闭流
}catch (Exception e){
e.printStackTrace();
}
}
}


四、截图



这里我们在项目目录下面可以看到,我的空文本word.txt中,写入了新的内容,就是那句“Hello world”;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐