zoukankan      html  css  js  c++  java
  • 使用I/O操作文件

    java.io包提供了一些接口和类,对文件进行基本的操作,包括对文件和目录属性的操作,对文件的读写等等。

    File类的常用方法:

    创建和删除文件

     Java中的流

    使用流的四个步骤

    1.创建File类

    2.创建合适的流

    3.读操作

    4.关闭流

    //1.创建File类
      File  file = new File("HelloWorld.txt");
      //2.创建合适的流
      FileInputStream  fis=null;
      try {
         fis = new FileInputStream(file);
        //3.读操作
       //调用FileInputStream  中的read()方法,一个一个字节的去读内容
       //直到读取到最后一个内容的时候  返回  -1
       int len = fis.read();
       while(len!=-1){
        //返回值不为-1则循环读取文件中内容并打印
        System.out.print((char)len);
        len=fis.read();
        
       }
       
      } catch (Exception e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
      }finally{
       //4.关闭流
       try {
        fis.close();
       } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
       }
      }

     我们在txt文档里面写了This is a test,就可以用如下代码读出来

  • 相关阅读:
    Power of Cryptography
    Radar Installation
    Emag eht htiw Em Pleh
    Help Me with the Game
    89. Gray Code
    87. Scramble String
    86. Partition List
    85. Maximal Rectangle
    84. Largest Rectangle in Histogram
    82. Remove Duplicates from Sorted List II
  • 原文地址:https://www.cnblogs.com/Jc1995/p/12907877.html
Copyright © 2011-2022 走看看