zoukankan      html  css  js  c++  java
  • 文件操作一

    一、             File

    File是整个java.io包中一个独立的类。此类的功能是完成与整个java平台无关的文件操作。

    创建文件示例代码如下:

    import java.io.File;

    public class FileDemo1 {

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

         // TODO Auto-generated method stub

         File file=new File("c:"+File.separator+"hi.demo");

         if(!file.exists()) file.createNewFile();

       }

    }

    二、             字节输出流:

    字节和字符最大的区别在于,字节不需要缓存,而字符需要缓存。

    字节输出流最大的父类是:OutputStream。需要子类实例化,示例代码如下:

    import java.io.File;

    import java.io.FileOutputStream;

    import java.io.IOException;

    import java.io.OutputStream;

    public class FileOutputStreamDemo {

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

         // TODO Auto-generated method stub

         File file=new File("c:"+File.separator+"hi.txt");

         if(!file.exists()) file.createNewFile();

         OutputStream out=new FileOutputStream(file);

         String str="hello world";

         byte[] bytes=str.getBytes();

         out.write(bytes);

         out.close();

       }

    }

    三、             字节输入流

    最大的父类是:InputStream,示例代码如下:

    import java.io.File;

    import java.io.FileInputStream;

    import java.io.FileNotFoundException;

    import java.io.InputStream;

    public class FileInputStreamDemo {

       /**

        * @param args

        * @throws FileNotFoundException 

        */

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

         File f=new File("c:"+File.separator+"hi.txt");

         InputStream in=new FileInputStream(f);

         byte[]  b=new byte[(int) f.length()];

         int len=in.read(b);

         System.out.println(new String(b,0,len));

         in.close();

       }

    }

    四、             字符输出流

    Writer:字符输出流,示例代码如下:

    import java.io.File;

    import java.io.FileWriter;

    import java.io.Writer;

    public class WriterDemo {

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

         // TODO Auto-generated method stub

         File file=new File("c:"+File.separator+"hi.txt");

         Writer w=new FileWriter(file,true);

         w.write("this is is writer");

         w.close();

       }

    }

  • 相关阅读:
    使用GUI工具Portainer.io管控Docker容器
    Pycharm-汉化的方法
    Python-Socketserver实现FTP,文件上传、下载
    Pycharm下载安装,本人亲测100% 破解
    Python-反射机制
    Python-操作XML文件
    Python-时间戳、元组时间的格式、自定义时间格式之间的转换
    Python-String字符串操作
    Python-生成器实现简单的"生产者消费者"模型
    Python- 装饰器
  • 原文地址:https://www.cnblogs.com/itfenqing/p/4429546.html
Copyright © 2011-2022 走看看