字节输入流:InputStream属于抽象类,用其子类FileInputStream进行实例化。(先定义字节数组,实例化输入流对象,读取文件内容到字节数组中,再输出)
第一种方式:
package 字节流;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class InputStreamDemo01 {
public static void main(String[] args) throws IOException{
File f=new File("f:"+File.separator+"File"+File.separator+"字节流.txt");
InputStream in=new FileInputStream(f);//字节流实例化
byte[] b=new byte[(int)f.length()];//新建一个字节数组,长度正好是文件的长度
in.read(b);//读取文件中的内容存储在字节数组中
in.close();//关闭输入流
System.out.println("长度:"+f.length());//输出文件的长度
System.out.println("内容为:"+new String(b));//输出文件内容
}
}
第二种方式:
package 字节流;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
public class InputStreamDemo {
public static void main(String[] args) throws Exception {
File f=new File("F:"+File.separator+"File"+File.separator+"字节流.txt");
InputStream in=new FileInputStream(f);
byte[] b=new byte[100];//先建立足够长的字节数组
int len=in.read(b);//见内容读入数组中,并返回长度
in.close();
System.out.println("长度:"+len);
System.out.println("内容:"+new String(b,0,len));
}
}
字节输出流:(先定义字符串,再将字符串转化为字节数组,实例化字节输入流对象,将字节数组写入文件)
package 字节流;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class OutputStreamDemo01 {
public static void main(String[] args)throws IOException {
OutputStream out=new FileOutputStream("F:"+File.separator+"File"+File.separator+"字节流.txt",true);//true表示追加内容
String str="\r\nhello wrold";//换行,追加内容
byte[] b=str.getBytes();//将字符串转化为字节数组
out.write(b);//将内容写入文件
out.close();//关闭输出流。
}
}