InputStream
单个字节逐一读取
public class testInputStream {
public static void main(String[] args){
File file=new File("E:\\Idea workspace\\IdeaProjects\\FirstMoudle\\src\\cn\\xjh\\io\\text");//也可以用相对路径
InputStream is=null;
int temp;//得到返回值,范围值为ASCII码值,可以转换为char显示
try {
is=new FileInputStream(file);//多态定义一个子类
while((temp=is.read())!=-1){
System.out.print((char)temp);//逐一打印
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
也可以定义一个缓冲数组 byte[] flush=new byte[1024] ,然后is.read(flush)每一次按数组大小1024字节读取。
public class testInputStream {
public static void main(String[] args){
File file=new File("E:\\Idea workspace\\IdeaProjects\\FirstMoudle\\src\\cn\\xjh\\io\\text");//从该文件中读取内容。
InputStream is=null;
byte[] flush=new byte[1024];//缓冲数组
int len;//得到返回值,返回值是当前接受的字节个数
try {
is=new FileInputStream(file);//若文件不存在则抛出异常
while((len=is.read(flush))!=-1){//将文件内容按缓冲数组大小读入缓存数组内,当返回为-1时全部读取完
String str=new String(flush,0,len,"utf8");//返回值len是当前接收字节个数,结束时返回-1
System.out.println(str);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
OutputStream
public static void main(String[] args) {
File src=new File("text01.txt");//定义一个等待写入的文件,如果不存在则自动创建
OutputStream os=null;
try {
os=new FileOutputStream(src,true);//将对象数据写入文件src内//
/*FileOutputStream(File file, boolean append) ,true代表不覆盖文件之前的内容,在后面添加。flase则覆盖重写*/
String s="四毛和傻曈";
byte[] datas=s.getBytes();
os.write(datas,0,datas.length);//数据,在数据偏移开始,写入字节数
os.flush();//刷新此输出流并强制写出所有缓冲的输出字节
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(os!=null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}