文件字节流(以字节为单位读取)
FileInputStream 文件字节输入流
FileOutputStream 文件字节输出流
package test;
import java.io.*;
public class test1{
public static void main(String[] args) {
File f=new File("word.txt");
FileOutputStream out=null;
try {
out=new FileOutputStream(f,true);//创建为输出流
//如果为true,则在末尾添加数据,没有或为false则更新后添加数据
String str="你见过林城四点的样子吗?";
byte b[]=str.getBytes();//字符串转化为字节数组
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();
}
}
}
FileInputStream in=null;
try {
in=new FileInputStream(f);
byte b2[]=new byte[1024];//字符串转换为字节数组
int num=in.read(b2);//
System.out.println("文件中的数据是:"+new String(b2,0,num));
}catch(FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}
finally {
if(in!=null) {
try {
in.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
}
}
文件字符流(以字符为单位进行读写)
FileReader 文件字符输入流
FileWriter 文件字符输出流
package test;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class test1{
public static void main(String[] args) {
File f=new File("word.txt");
FileWriter fw=null; //字符输入流
try {
fw=new FileWriter(f,true);//true是在文件后添加内容,不写或false则为替换文件中的内容
String str="自强不息,厚德载物";
fw.write(str); //将字符串写入到文本文档
}catch(IOException e){
e.printStackTrace();
}finally {
if(fw!=null) {
try {
fw.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
FileReader fr=null;//字符输出流
try {
fr=new FileReader(f); //关联起来
char ch[]=new char[1024]; //定义一个缓冲区
int count;
while((count=fr.read(ch))!=-1) {//此时count是读取到的长度
System.out.println("文件中的内容为:"+new String(ch,0,count));
}
}catch(FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}finally {
if(fr!=null) {
try {
fr.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
}
}