黑马程序员------学习笔记(5)IO流中字节流操作

——- android培训java培训、期待与您交流! ———-

1.file操作
2.输入输出流

学java,android,ios等等都离不开对file的操作

/*
 * 使用File类操作文件
 * 1.查看文件属性
 * 2.新建文件(File类的createNewFile()方法)
 * 3.删除文件(File类的delete()方法)
 */
public class Test {

    public static void main(String[] args) throws IOException  {

        File f = new File("c:/myDoc/hello.txt");
System.out.println("文件名:"+f.getName());
System.out.println("路径:"+f.getParent());
System.out.println("绝对路径:"+f.getAbsolutePath());
System.out.println(f.exists() ?"文件存在":"文件不存在");
System.out.println(f.isDirectory()?"文件是目录":"文件不是目录");
System.out.println(f.isFile()?"文件是普通文件":"文件是命名管道,也可能是个目录");
System.out.println(f.canRead()?"可以读取此文件":"不可以读取此文件");//文件是否可读
System.out.println(f.canWrite()?"可以写入到此文件":"不可以写入到此文件");//文件是否可写
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date =new Date(f.lastModified());
System.out.println(sdf.format(date));
//新建文件
if(!f.exists()){
    f.createNewFile();
}

//删除文件
if(f.exists()){
    f.delete();
}
}

}
/*
 * FileInputStream
 * 1、read()方法读取文件内容,返回一个int值
 * 2、需要转换字符
 * 3、read()方法是“单程”的
 * 4、一定要关闭流,变成习惯!!
 */
public class InputstreamTest {

    public static void main(String[] args) throws IOException {
        FileInputStream fis = new FileInputStream("c:/my/hello.txt");
       int data;
       System.out.println("可读取字节数:"+fis.available());
       System.out.println("======开始读取文件内容======");
       //循环读取数据
       while((data=fis.read())!= -1){
           System.out.print(data + " ");
       }

       System.out.println();
       System.out.println("======文件内容读取完毕======");
       System.out.println("======将字节文件内容转化成字符串,然后查看文件内容======");
       while((data=fis.read())!= -1){
           char c=(char)data;
           System.out.print(c);
       }

       System.out.println();
       System.out.println("==============文件字符串内容读取完毕==============");
      //关闭流对象
       fis.close();

    }

}
/*
 * FileOutputStream
 * 1、通过write()方法进行写操作
 * 2、FileOutputStream可以自动创建文件
 * 3、必须关闭流
 */


public class OutputStreamTest {

    public static void main(String[] args) throws IOException{
        //实例化FileOutputStream对象
          FileOutputStream fos = new FileOutputStream("c:/my/hello.txt",true);
          String str = "好好学习,天天向上!";
          byte [] words = str.getBytes();
          fos.write(words,0, words.length);
          System.out.println("文件已经更新完毕!");
          //必须关闭流
          fos.close();
    }

}

以上三个test组合的思路
1.创建file,判断文件存不存在,不存在进行创建
2.通过FileOutputStream输出内容到文件中
3.通过FileInputStream输入文件内容,并在控制台打印
注意:字节与字符之间的转换

——- android培训java培训、期待与您交流! ———-

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值