欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java IO 之文件读写简单实例

程序员文章站 2023-12-04 14:29:04
java io 之文件读写简单实例 1.文件读 public class readfromfile { /** * 以字节为单位读取文件,常用于读...

java io 之文件读写简单实例

1.文件读

public class readfromfile {
  /**
   * 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。
   */
  public static void readfilebybytes(string filename) {
    file file = new file(filename);
    inputstream in = null;
    try {
      system.out.println("以字节为单位读取文件内容,一次读一个字节:");
      // 一次读一个字节
      in = new fileinputstream(file);
      int tempbyte;
      while ((tempbyte = in.read()) != -1) {
        system.out.write(tempbyte);
      }
      in.close();
    } catch (ioexception e) {
      e.printstacktrace();
      return;
    }
    try {
      system.out.println("以字节为单位读取文件内容,一次读多个字节:");
      // 一次读多个字节
      byte[] tempbytes = new byte[100];
      int byteread = 0;
      in = new fileinputstream(filename);
      readfromfile.showavailablebytes(in);
      // 读入多个字节到字节数组中,byteread为一次读入的字节数
      while ((byteread = in.read(tempbytes)) != -1) {
        system.out.write(tempbytes, 0, byteread);
      }
    } catch (exception e1) {
      e1.printstacktrace();
    } finally {
      if (in != null) {
        try {
          in.close();
        } catch (ioexception e1) {
        }
      }
    }
  }

  /**
   * 以字符为单位读取文件,常用于读文本,数字等类型的文件
   */
  public static void readfilebychars(string filename) {
    file file = new file(filename);
    reader reader = null;
    try {
      system.out.println("以字符为单位读取文件内容,一次读一个字节:");
      // 一次读一个字符
      reader = new inputstreamreader(new fileinputstream(file));
      int tempchar;
      while ((tempchar = reader.read()) != -1) {
        // 对于windows下,\r\n这两个字符在一起时,表示一个换行。
        // 但如果这两个字符分开显示时,会换两次行。
        // 因此,屏蔽掉\r,或者屏蔽\n。否则,将会多出很多空行。
        if (((char) tempchar) != '\r') {
          system.out.print((char) tempchar);
        }
      }
      reader.close();
    } catch (exception e) {
      e.printstacktrace();
    }
    try {
      system.out.println("以字符为单位读取文件内容,一次读多个字节:");
      // 一次读多个字符
      char[] tempchars = new char[30];
      int charread = 0;
      reader = new inputstreamreader(new fileinputstream(filename));
      // 读入多个字符到字符数组中,charread为一次读取字符数
      while ((charread = reader.read(tempchars)) != -1) {
        // 同样屏蔽掉\r不显示
        if ((charread == tempchars.length)
            && (tempchars[tempchars.length - 1] != '\r')) {
          system.out.print(tempchars);
        } else {
          for (int i = 0; i < charread; i++) {
            if (tempchars[i] == '\r') {
              continue;
            } else {
              system.out.print(tempchars[i]);
            }
          }
        }
      }

    } catch (exception e1) {
      e1.printstacktrace();
    } finally {
      if (reader != null) {
        try {
          reader.close();
        } catch (ioexception e1) {
        }
      }
    }
  }

  /**
   * 以行为单位读取文件,常用于读面向行的格式化文件
   */
  public static void readfilebylines(string filename) {
    file file = new file(filename);
    bufferedreader reader = null;
    try {
      system.out.println("以行为单位读取文件内容,一次读一整行:");
      reader = new bufferedreader(new filereader(file));
      string tempstring = null;
      int line = 1;
      // 一次读入一行,直到读入null为文件结束
      while ((tempstring = reader.readline()) != null) {
        // 显示行号
        system.out.println("line " + line + ": " + tempstring);
        line++;
      }
      reader.close();
    } catch (ioexception e) {
      e.printstacktrace();
    } finally {
      if (reader != null) {
        try {
          reader.close();
        } catch (ioexception e1) {
        }
      }
    }
  }

  /**
   * 随机读取文件内容
   */
  public static void readfilebyrandomaccess(string filename) {
    randomaccessfile randomfile = null;
    try {
      system.out.println("随机读取一段文件内容:");
      // 打开一个随机访问文件流,按只读方式
      randomfile = new randomaccessfile(filename, "r");
      // 文件长度,字节数
      long filelength = randomfile.length();
      // 读文件的起始位置
      int beginindex = (filelength > 4) ? 4 : 0;
      // 将读文件的开始位置移到beginindex位置。
      randomfile.seek(beginindex);
      byte[] bytes = new byte[10];
      int byteread = 0;
      // 一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。
      // 将一次读取的字节数赋给byteread
      while ((byteread = randomfile.read(bytes)) != -1) {
        system.out.write(bytes, 0, byteread);
      }
    } catch (ioexception e) {
      e.printstacktrace();
    } finally {
      if (randomfile != null) {
        try {
          randomfile.close();
        } catch (ioexception e1) {
        }
      }
    }
  }

  /**
   * 显示输入流中还剩的字节数
   */
  private static void showavailablebytes(inputstream in) {
    try {
      system.out.println("当前字节输入流中的字节数为:" + in.available());
    } catch (ioexception e) {
      e.printstacktrace();
    }
  }

  public static void main(string[] args) {
    string filename = "c:/temp/newtemp.txt";
    readfromfile.readfilebybytes(filename);
    readfromfile.readfilebychars(filename);
    readfromfile.readfilebylines(filename);
    readfromfile.readfilebyrandomaccess(filename);
  }
}

2. 文件写

public class appendtofile {
  /**
   * a方法追加文件:使用randomaccessfile
   */
  public static void appendmethoda(string filename, string content) {
    try {
      // 打开一个随机访问文件流,按读写方式
      randomaccessfile randomfile = new randomaccessfile(filename, "rw");
      // 文件长度,字节数
      long filelength = randomfile.length();
      //将写文件指针移到文件尾。
      randomfile.seek(filelength);
      randomfile.writebytes(content);
      randomfile.close();
    } catch (ioexception e) {
      e.printstacktrace();
    }
  }

  /**
   * b方法追加文件:使用filewriter
   */
  public static void appendmethodb(string filename, string content) {
    try {
      //打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件
      filewriter writer = new filewriter(filename, true);
      writer.write(content);
      writer.close();
    } catch (ioexception e) {
      e.printstacktrace();
    }
  }

  public static void main(string[] args) {
    string filename = "c:/temp/newtemp.txt";
    string content = "new append!";
    //按方法a追加文件
    appendtofile.appendmethoda(filename, content);
    appendtofile.appendmethoda(filename, "append end. \n");
    //显示文件内容
    readfromfile.readfilebylines(filename);
    //按方法b追加文件
    appendtofile.appendmethodb(filename, content);
    appendtofile.appendmethodb(filename, "append end. \n");
    //显示文件内容
    readfromfile.readfilebylines(filename);
  }
}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!