4月26日学习总结-----字节输入输出流

一,File创建文件
File file =new File("F:\\陈京旗.txt");         //引用File类,构建文件镜像对象    也可以是File file =new File("F:/陈京旗.txt");
file.exists();                                                  //判断文件或则目录是否存在,布尔类型
file.createNewFile();                                    //创建文件
file.getName()                                            //查看文件名称
file.getAbsolutePath()                                //查看绝对路径(全路径)
file.getPath()                                              //查看相对路径
file.length()                                                //查看文件大小(字节)
例:

try {
   //创建一个文件
   //实例化 File
   File file=new File("F:/陈京旗.txt");
   if (!file.exists()) {
   
   }else{
     file.delete(); //删除文件
    file.createNewFile();  //创建文件
    System.out.println("是文件吗?"+file.isFile());   //file.isFile()   判断是否为文件
     System.out.println("文件名:"+file.getName());   //ile.getName() 获取文件名
    System.out.println("绝对路径:"+file.getAbsolutePath());    //file.getAbsolutePath() 获取绝对路径
     System.out.println("相对路径:"+file.getPath());    //file.getPath() 获取相对路径
     Long size=file.length();
     System.out.println("内容大小:"+size+"字节");    //获取文件字节大小 ,单个英文字母是一个字节,单个中文是2个字节
   }
  } catch (IOException e) {
   
   e.printStackTrace();
  }
二.InputStream(输入流)——>(读取)

首先实例化 FileInputStream 类,通过 .read(); 方法读取元素,根据字符情况可能需要转换
.read();                              //读取数据
.close();                             //关闭流
try {
                           
   FileInputStream fis =new FileInputStream("F:\\陈京旗.txt"); //引用指定文件目录 内容为abc

int leng=0; //声明整形int型变量leng用于存储数据
while ((leng=fis.read())!=-1) { //依次读取数据直到空(-1)为止,并放倒leng变量中
System.out.println((char)leng);
//leng出来的是ascii码,需要使用Char强转成相应字
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
三.OutputStream(输出流)——>(写入)

先实例化FileOutputStream对象并引用目录,通过变量名.write()方法写入相应信息

.write();                              //写入信息
.close();                             //关闭流
.flush                                //清空缓存
                         OutputStream os = null;                                   //实例化类

try {
os =new FileOutputStream("D:\\陈京旗.txt"); //引用指定文件目录

String str = "好好学习,天天向上"; //需要插入的字符

byte [ ] b = str.getBytes(); //因中文一字等于两字节,需使用byte储存
os.write(b, 0, b.length); //使用write方法(变量,位置,位置)

} catch (FileNotFoundException e) {

e.printStackTrace();
} catch (IOException e) {

e.printStackTrace();
}finally{
try {
os.close(); //关闭流
} catch (IOException e) {

e.printStackTrace();
}
}

猜你喜欢

转载自blog.csdn.net/chenjingqi101/article/details/80104098
今日推荐