java IO 流(二)
yte();// 一个一个字节读出来
}
myname = new String(b);
myage = raf.readInt();// 读取年龄
System.out.println("我的年龄是:" + myage + ",我的姓名是:" + myname);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
这样操作很麻烦,所以java有专门的管理方法:字节流与字符流:
三, 字节与字符流(OutputStream,InputStream, Reader,Writer四个抽象类)
操作步骤:
1,使用Files类打开文件
2,通过字节流或字符流的子类,指定输出位置
3,进行读写操作
4,关闭输入/输出(资源操作最后必须关闭,否则可能出现未知错误)
1,字节流: public abstract class OutputStream extends Object implements Clonseable, Fluashable
Clonseable 表示可以关闭的操作,因为程序运行到最后肯定要关闭(close())
Fluashable 表示刷新,清空内在中的数据(flush())
OutputStrem:
File f = new File("f:" + File.separator + "test.txt");
OutputStream os = null;
try {
os = new FileOutputStream (f);//向上转型,如果文件不存在,会自动创建,如果存在,会覆盖
String s = "I am Chinese";
byte [] b = s.getBytes();//转化
try {
os.write(b);//会把之前的删除
int a = 3;
os.write(a);
os.write(b, 5, 7);//从第4个字符开始,一共7个字符,可以取到Chinese
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {//在最后关闭,不管是否出现异常,都会执行
try {
if(os != null){
os.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//如果要想保留之前的内容
try {
os = new FileOutputStream(f,true);//表示在文件后面追加内容
try {
os.write("\r\n我叫钟志钢".getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {//在最后关闭,不管是否出现异常,都会执行
try {
if(os != null){
os.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
InputStream:
File f = new File("f:" + File.separator + "test.txt");
InputStream is = null;
try {
is = new FileInputStream (f);
byte b [] = new byte[1024];//定义一个1024个字节的数据
try {
// is.read(b);//把所有内容都读取到b中(最大是1024),如果不确定文件的大小,可以利用如下方法:
// int len = is.available();//也可以用: int len = f.lenght;
// byte[] b2 = new byte[len];
// is.read(b2);
//或者从读取的数据时定义大小
// int lens = is.read(b);
// String s = new String(b, 0, lens);
//is.read();//一个一个读取
// for(int i = 0; i < b.length; i ++){
// b[i] = (byte) is.read();
// //当读到末尾时,就会出现b[i] = -1
// }
// System.out.println("is.read()"+new String(b));
//以上方法的改进
int len = 0;
int lend = 0;//读到的数据
while((lend = is.read()) != -1){
b[len] = (byte) lend;
len++;
System.out.println(lend);
}
System.out.println("输入流的数据:" + new String(b));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(is != null){
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
2, 字符流可以
| 评论 |
|
|