FileInputStream,FileOutputStream(文件字节输入输出流)读写文件
注:IO流使用完之后 记得关闭,释放资源
/**
* FileOutputStream FileInputStream Test
*
* @author xiazhang
* @date 2017-6-4
*/
public class FileOutInputStreamTest {
/**
* 读文件
*/
private static void readFile(File file){
try {
FileInputStream fis = new FileInputStream(file);
//每次读取一个字节
/*int content = fis.read();
//content != -1 表示读到结束的标记
while(content != -1){
System.out.print((char)content);
content = fis.read();
}*/
/*int num = 1;//读取次数
byte[] b = new byte[20];
//从此输入流中将最多 b.length 个字节的数据读入一个 byte 数组中
//每次读取20个字节到byte数组中
//返回的int表示读到此数组中的实际长度
int len = fis.read(b);
while(len != -1){
System.out.print(new String(b,0,len));
len = fis.read(b);
if(len != -1){
num++;
}
}
//结果:共读取5次
System.out.println("读取次数:"+num);*/
int num = 1;//读取次数
byte[] b = new byte[20];
//从此输入流中将最多 5 个字节的数据读入一个 byte 数组中
int len = fis.read(b, 1, 5);
while(len != -1){
System.out.println(new String(b,1,len));
len = fis.read(b, 1, 5);
if(len != -1){
num ++;
}
}
//结果:共读取17次
System.out.println("读取次数:"+num);
//流必须关闭 释放资源
fis.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 写入文件
*/
private static void writeFile(File file){
try {
FileOutputStream fos = new FileOutputStream(file);
//写入字节
fos.write(97);
fos.write(98);
fos.write(99);
//关闭流 释放资源
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO: handle exception
}
}
public static void main(String[] args) {
File file = new File("fileTest3.txt");
if(!file.exists()){//检查文件是否存在
/*try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
System.out.println(file.getName()+"不存在!");
}else{
readFile(file);
writeFile(file);
}
}
}