输入流:InputStream //创建输入流对象,读取文件,但必须抛异常
fis = new FileInputStream("F:\\IdeaProjects\\Java-Api\\file\\hello.txt");
返回的整数数据:available()
fis.available()可以拿到这个文件的所有字节数
read()方法可以读取此文件夹所有的字节,每次只能读取一个字节,所以要使用byte[]去读取全部字节
while ((fis.read(bytes))!=-1){
String s = new String(bytes, "utf-8");
System.out.println(s);
}
close()关闭输入流,需要抛异常加判断
try {
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
输出流:FileOutputStream
1:通过构造器创建字节输出流对象,用于写入文件
2:第二个参数如果不写默认false替换原来内容,如果是true追加内容
FileOutputStream fos = null;
try {
fos = new FileOutputStream("F:\\IdeaProjects\\Java-Api\\file\\xs.txt",true);
}catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
write():写入数据到目标程序,getBytes()获取所有的字节
String str = "flush强制把缓冲区的数据写到输出流中";
//fos.write(65);
byte[] bytes = str.getBytes();
fos.write(bytes,0,bytes.length);
close()关闭输出流,需要抛异常加判断
try {
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}