输出流操作步骤 FileOutputStream
1.打开输出流
2.写数据
3.关闭流
FileOutputStream fileOutputStream = null; //1.打开输出流
try {
fileOutputStream = new FileOutputStream(file);
//write(int b);//写入一个字节的数据.
//write(byte[] b); //写入多个字节的数据
//write(byte[] b,int off,int len);//off为b开始的偏移量,len为长度
//写一个字节的数据
fileOutputStream.write( 98 );
//写多个字节的数据
String s = "hello";
fileOutputStream.write(s.getBytes());
//通过指定byte的指定位置来写
byte[] bytes = s.getBytes();
fileOutputStream.write( bytes,1,2 );
fileOutputStream.flush(); //调用这个方法 就会直接从内存的内核空间转移到目的源(磁盘)上.
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try { //关闭流
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
输入流操作步骤
1.打开输入流
2.写数据
3.关闭流
FileInputStream fileInputStream = null; //打开输入流
try {
fileInputStream = new FileInputStream( file );
//从数据中每次读一个字节,并且返回是一个字节 读到最后一个位置返回-1.
int i;
// while ((i = fileInputStream.read()) != -1){
// System.out.print((char)i);
//}
System.out.println();
//读取一个数组,返回的是实际存储数据的大小 如果没有可以读的了返回-1,
byte[] bytes = new byte[100];
int read = fileInputStream.read(bytes);
System.out.println(new String( bytes ));
System.out.println(read);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}