java 读取文件方法的总结

java 读取文件方法的总结

1、按字节读取 文件 内容
2、按字符读取 文件 内容
3、按行读取 文件 内容
4、随机读取 文件 内容

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);
  }
}

5、将内容追加到文件 尾部

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);
  }
}

以上就是java 读取文件的方法总结,如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

(0)

相关推荐

  • Java Servlet上传图片到指定文件夹并显示图片

    在学习Servlet过程中,针对图片上传做了一个Demo,实现的功能是:在a页面上传图片,点击提交后,将图片保存到服务器指定路径(D:/image):跳转到b页面,b页面读取展示绝对路径(D:/image)的图片.主要步骤如下: 步骤一:上传页面uploadphoto.jsp 需要注意两个问题: 1.form 的method必须是post的,get不能上传文件, 还需要加上enctype="multipart/form-data" 表示提交的数据是二进制文件. 2.需要提供type=&

  • Java文件(io)编程之记事本开发详解

    本文实例为大家分享了Java开发简易记事本的具体代码,供大家参考,具体内容如下 public class NotePad extends JFrame implements ActionListener{ //定义需要的组件 JTextArea jta=null; //多行文本框 JMenuBar jmb=null; //菜单条 JMenu jm1=null; //菜单 JMenuItem jmi1=null,jmi2=null; //菜单项 public static void main(St

  • FasfDFS整合Java实现文件上传下载功能实例详解

    在上篇文章给大家介绍了FastDFS安装和配置整合Nginx-1.13.3的方法,大家可以点击查看下. 今天使用Java代码实现文件的上传和下载.对此作者提供了Java API支持,下载fastdfs-client-java将源码添加到项目中.或者在Maven项目pom.xml文件中添加依赖 <dependency> <groupId>org.csource</groupId> <artifactId>fastdfs-client-java</arti

  • Java文件(io)编程之文件字符流使用方法详解

    本文实例为大家分享了文件字符流的使用方法,供大家参考,具体内容如下 案例1: 读取一个文件并写入到另一个文件中,char[] 来中转. 首先要在E盘下创建一个文本文档,命名为test.txt,输入一些字符串. public class Demo_5 { public static void main(String[] args) { FileReader fr=null; //文件取出字符流对象(输入流) FileWriter fw=null; //写入到文件(输出流) try { fr=new

  • 基于java文件上传-原始的Servlet方式

    前言:干了这几个项目,也做过几次文件上传下载,要么是copy项目以前的代码,要么是百度的,虽然做出来了,但学习一下原理弄透彻还是很有必要的.刚出去转了一圈看周围有没有租房的,在北京出去找房子是心里感觉最不爽的时候,没有归属感,房租还不便宜,RT,不能好高骛远,还是脚踏实地一点一点学技术吧,终将有一日,工资会涨的. java文件上传 传统的文件上传,不用jquery插件的话,就是用form表单提交,项目里用过uploadify,可以异步上传文件,原理我也没研究.现在说传统的form表单上传文件.

  • Java如何在不存在文件夹的目录下创建文件

    核心代码如下所示: 1. String strPath = "E:\\a\\aa\\aaa.txt"; File file = new File(strPath); if(!file.exists())){ file.file.mkdirs(); } 2. String strPath = "E:\\a\\aa\\aaa.txt"; File file = new File(strPath); File fileParent = file.getParentFile

  • Java实现文件分割和文件合并实例

    文件切割和文件合并这个问题困扰了我有一段时间了(超过一天没做粗来). 找了好多博客,本来想转载一个来的 结果找不到了.很无奈. 只好自己贴代码上了. 当然我会尽力好好写注释的. 文件切割器: import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.util.Scanner; public c

  • java 读取文件方法的总结

    java 读取文件方法的总结 1.按字节读取 文件 内容 2.按字符读取 文件 内容 3.按行读取 文件 内容 4.随机读取 文件 内容 public class ReadFromFile { /** * 以字节为单位读取文件,常用于读二进制文件,如图片.声音.影像等文件. */ public static void readFileByBytes(String fileName) { File file = new File(fileName); InputStream in = null;

  • Java读取文件方法汇总

    本文实例为大家分享了Java读取文件的方法,供大家参考,具体内容如下 1.按字节读取文件内容 2.按字符读取文件内容 3.按行读取文件内容 4.随机读取文件内容 public class ReadFromFile { /** * 以字节为单位读取文件,常用于读二进制文件,如图片.声音.影像等文件. */ public static void readFileByBytes(String fileName) { File file = new File(fileName); InputStream

  • Java 读取文件方法大全

    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); in

  • Java读取文件的简单实现方法

    本文实例讲述了Java读取文件的简单实现方法,非常实用.分享给大家供大家参考之用.具体方法如下: 这是一个简单的读取文件的代码,并试着读取一个log文件,再输出. 主要代码如下: import java.io.*; public class FileToString { public static String readFile(String fileName) { String output = ""; File file = new File(fileName); if(file.

  • java 读取文件路径空格、"+"和中文的处理方法

    有时候在java代码中读取文件,如果文件所在路径包含空格."+"号或者是中文的时候,由于这些特殊的字符会被进行编码转译,所以就会报没有发现文件的错误,那么遇到这种错误,我们就要把编码过后的路径进行解码,这样才能正确的找到文件.主要的解决方法有一下三种方法: 解决方法 1.替换法 比如文件路径如果存在空格,那么会被转译成"%20",那么就可以利用字符串替换,把"%20"传化成空格,这样就能正确的找到文件了.这是这种如此暴力,低级的处理方法,一般有经

  • java读取文件内容为string字符串的方法

    直接就把项目中的方法贴出来吧 /** * 读出城市列表文件 */ private String readCityFile() { File file02 = new File(path_xinfu, "/cityList.json"); FileInputStream is = null; StringBuilder stringBuilder = null; try { if (file02.length() != 0) { /** * 文件有内容才去读文件 */ is = new

  • Java读取文件及基于正则表达式的获取电话号码功能详解

    本文实例讲述了Java读取文件及基于正则表达式的获取电话号码功能.分享给大家供大家参考,具体如下: 1.正则表达式 正则表达式,又称 正规表示法 . 常规表示法 (英语:Regular Expression,在代码中常简写为regex.regexp或RE),计算机科学的一个概念.正则表达式使用单个字符串来描述.匹配一系列符合某个句法规则的字符串.在很多文本编辑器里,正则表达式通常被用来检索.替换那些符合某个模式的文本. 用到的一些特殊构造正则表达式的意义解析: ? 当该字符 紧跟在任何一个其他限

  • Java读写文件方法总结(推荐)

    Java的读写文件方法在工作中相信有很多的用处的,本人在之前包括现在都在使用Java的读写文件方法来处理数据方面的输入输出,确实很方便.奈何我的记性实在是叫人着急,很多时候既然都会想不起来怎么写了,不过我的Java代码量也实在是少的可怜,所以应该多多练习.这里做一个总结,集中在一起方面今后查看. Java读文件 package 天才白痴梦; import java.io.BufferedReader; import java.io.File; import java.io.FileInputSt

  • java读取文件和写入文件的方式(简单实例)

    Java代码 public class ReadFromFile { /** * 以字节为单位读取文件,常用于读二进制文件,如图片.声音.影像等文件. */ public static void readFileByBytes(String fileName) { File file = new File(fileName); InputStream in = null; try { System.out.println("以字节为单位读取文件内容,一次读一个字节:"); // 一次读

  • java读取文件内容,解析Json格式数据方式

    目录 java读取文件内容,解析Json格式数据 一.读取txt文件内容(Json格式数据) 二.解析处理Json格式数据 三.结果存入数据库 四.测试 java 读取txt文件中的json数据,进行导出 以下代码可直接运行 java读取文件内容,解析Json格式数据 一.读取txt文件内容(Json格式数据) public static String reader(String filePath) { try { File file = new File(filePath); if (file

随机推荐