package fileIO;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* 一般在操作文件流时,不管字节流还是字符流,都可以按照以下方式进行
* (1) 使用file类找到一个文件
* (2) 通过file类的对象去实例化字节流或字符流的子类。
* (3) 进行字节(字符)的读写操作。
* (4) 关闭文件流。
* */
public class StreamDemo {
public static void main(String[] args) {
File f = new File("D:\\temp.txt");//通过File类找到D盘下的temp.txt文件
OutputStream out = null;//声明输出字节流
try{
out = new FileOutputStream(f); //通过File类对象去实例化OutputStream类的对象
}catch(FileNotFoundException e){
e.printStackTrace();
}
byte b[] = "Hello World!!!".getBytes();//字节流主要是以byte数组为主,将字符串转化成字符数组
try{
out.write(b);//调用OutputStream类中的write()方法,将byte数组中的内容写到文件中
}catch(IOException e1){
e1.printStackTrace();
}
try{
out.close();//调用OutputStream类中的close()方法,关闭数据流操作
}catch(IOException e2){
e2.printStackTrace();
}
//以下为读文件操作
InputStream in = null;//声明输入字节流
try{
in = new FileInputStream(f);//通过File去实例化InputStream的对象
}catch(FileNotFoundException e3){
e3.printStackTrace();
}
//开辟一个空间用于接收文件读进来的数据
byte b1[] = new byte[1024];
int i = 0;
try{
//将b1的引用传递到read()方法之中,同时此方法返回读入数据的个数
i = in.read(b1);
}catch(IOException e4){
e4.printStackTrace();
}
try{
in.close();//调用InputStream类中的close()方法,关闭数据流操作
}catch(IOException e5){
e5.printStackTrace();
}
System.out.println(new String(b1,0,i));//将byte数组转化成字符串输出
}
}
java字节流
最新推荐文章于 2025-06-11 15:55:36 发布