1、File
1)构造方法
2)创建
3)判断、获取
4)删除
2、字节流
1)字节流写数据的3种方式
FileOutputStream fos = new FileOutputStream("e:\\a.txx");
//将字符转为字节
Bytes[]bytes = "abcdefffjdlsajflasdfjklasdf".getBytes();
fos.write(bytes,0,bytes.length);
//关闭资源
fos.close();
2)字节流写数据实现换行
fos.write("\rn\".getBytes());
windows:\r\n
linux:\n
mac:\r
3)字节流写数据实现追加
FileOutputStream fos = new FileOutputStream("e:\\a.txx",true);
//加上true之后,就是从文件的末尾写入,不加true,默认是从文件的开头写入
4)异常处理
FileOutputStream fos = null;
try{
fos = new FileOutputStream("e:\\a.txx",true);
}catch(IOExcetion p){
e.printStackTrace();
}finally{
//不管文件读写有没有出错,最后一定要 close资源
if(fos !=null) fos.close();
}
3、读写文件
1)读取文件
//读取文件的数据,读物1024整数个字节
public static void readFile2()throws IOException {
FileInputStream input =new FileInputStream("e:\\file.txt");
//读取1024字节及其整数倍
byte[]bytes =new byte[1024];
//单次读取的长度
int len;
while ((len =input.read(bytes)) != -1){
System.out.println("长度:"+len);
System.out.println(new String(bytes,0,len));
}
2)写入文件,读1024整数倍个字节
//实现将file.txt内容写入到file2.txt,读取1024整数倍个字节
public static void readAndWrite() throws IOException {
//先创建file2.txt
FileOutputStream out = new FileOutputStream("e:\\file2.txt",true);
//获得file.txt,用于读取文件
FileInputStream input = new FileInputStream("e:\\file.txt");
//装读取文件的流
byte[] b = new byte[1024];
//装单次读入大小
int len;
//读取文件数据
while((len = input.read(b)) != -1){
//将数据写入到file2.txt
out.write(b,0,len);
}
out.close();
input.close();
}
3)读取1个字节就写入一个字节
4、复制图片
//复制图片
public static void readPicture() throws IOException {
//图片目的地
FileOutputStream out = new FileOutputStream("e:\\pic.png");
//图片原始位置
FileInputStream inputStream =new FileInputStream("e:\\25.png");
//存取单次读入的数据