要读取一个文件,有以下几个步骤:
1.建立与文件的联系:File对象,文件必须存在
2.选择流:按字节流读取,文件输入流 InputStream FileInputStream
3.操作:byte[] car=new byte[1024]+read
4.释放资源,注意jdk1.7后会自动关闭了
InputStream是一个抽象类,不能new一个新的对象,所以这里使用多态
InputStream is=new FileInputStream(......);
选择构造方法,第一个和第三个比较常用,本质上来说这两种方法是一致的,通过String name 创建一个新对象,
它内部还是会通过name包装成File
在读取文件时,使用循环不断进行读取,定义一个制定长度的byte数组,则这个数组就是每次读取文件的长度,
如果要输出,就创建一个String对象,String info = new String(car, 开始, 结束);
public class Demo02 {
public static void main(String[] args) {
File src = new File("F:/Picture/test.txt");
InputStream is = null;
try {
is = new FileInputStream(src);
// 缓冲数组
byte[] car = new byte[8];
// 实际读取大小
int len = 0;
// 循环读取
while (-1 != (len = is.read(car))) {
// 输出 字节数组转为字符串
String info = new String(car, 0, len);
System.out.println(info);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
文件写出,有以下几个步骤:
1.建立与文件的联系:File对象,文件可不存在
2.选择流:按字节流写出,文件输出流 OutputStream FileOutputStream
3.操作:write+flush
4.释放资源,注意jdk1.7后会自动关闭了
FileOutputStream的构造方法
FileOutputStream(File file,boolean append) 如果选择true,则是追加,false则覆盖
构造方法中没有append参数的,则默认false,覆盖
public class Demo02 {
public static void main(String[] args) {
File dest=new File("F:/Picture/test.txt");
OutputStream os=null;
try {
os=new FileOutputStream(dest);
String str="hahahaha";
//字符串转字节数组
byte[] data=str.getBytes();
os.write(data,0,data.length);
//强制刷新出去
os.flush();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
if(null!=os){
os.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}