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

 更新时间:2016年05月31日 16:49:46   投稿:jingxian  
下面小编就为大家带来一篇Java读写文件方法总结(推荐)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧

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

Java读文件

package 天才白痴梦;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.io.Reader;

public class JavaIO {
  
  /**
   * 采用的是操作系统底层默认的编码方式,GBK等,非UTF8
   * */
  
  /**
   * 以字节为单位读取文件内容,常用于读取二进制文件,比如图片、影像、声音等文件
   * */
  public static void readFileByBytes(String filename) {
    File file=new File(filename);
    FileInputStream in=null;
    try {
      System.out.println("以字节为单位读取文件,一次读一个字节: ");
      in=new FileInputStream(file);
      int temp=0;
      while ((temp=in.read()) != -1) {
        System.out.println(temp);
      }
      in.close();
    } catch (IOException e) {
      e.printStackTrace();
      return ;
    }
    try {
      System.out.println("以字节为单位读取文件,一次读多个字节: ");
      byte[] temp=new byte[100];
      int byteread=0;
      in=new FileInputStream(file);
      JavaIO.showAvailableBytes(in);
      while ((byteread=in.read(temp)) != -1) {
        System.out.write(temp,0,byteread);
      }
    } catch (Exception e1) {
      e1.printStackTrace();
    } finally {
      if (in != null) {
        try {
          in.close();
        } catch (IOException e1) {
          
        }
      }
    }
  }
  /**
   * 以字符为单位读取文件,常用于读文本,数字等类型的文件
   * */
  public static void readFileByChar(String filename) {
    File file=new File(filename);
    Reader reader=null;
    try {
      System.out.println("以字符为单位读取文件内容,一次一个字节:");
      //InputStreamReader类:是字节向字符转换的桥梁
      reader=new InputStreamReader(new FileInputStream(file));
      int temp;
      while ((temp=reader.read()) != -1) {
        if (((char)temp) != '\r') {
          System.out.println((char)temp);
        }
      } 
      reader.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
    try {
      System.out.println("以字符为单位读取文件内容,一次读多个字节: ");
      char[] temp=new char[30];
      int charread=0;
      reader=new InputStreamReader(new FileInputStream(filename));
      while ((charread=reader.read(temp)) != -1) {
        if ((charread == temp.length) && (temp[temp.length-1]!='\r')) {
          System.out.println(temp);
        } else {
          for (int i=0; i<charread; i++) {
            if (temp[i] == '\r') {
              break;
            } else {
              System.out.println(temp[i]);
            }
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (reader != null) {
        try {
          reader.close();
        } catch (IOException e) {
          
        }
      }
    }
  }
  /**
   * 以行为单位读取文件,常用于读面向行的格式化文件
   * */
  public static void readFileByLine(String filename) {
    File file=new File(filename);
    BufferedReader reader=null;
    try {
      System.out.println("以行为单位读取文件内容,一次读一整行: ");
      reader=new BufferedReader(new FileReader(file));
      String temp=null;
      int line=1;
      while ((temp=reader.readLine()) != null) {
        System.out.println("line " + line + ": " + temp);
        line++;
      }
      reader.close();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (reader != null) {
        try {
          reader.close();
        } catch (IOException e) {
          
        }
      }
    }
  }
  /**
   * 随机读取文件内容
   * */
  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);
      randomfile.seek(beginIndex);
      byte[] bytes=new byte[10];
      int byteread=0;
      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 e) {
          
        }
      }
    }
  }
  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="E:\\BaiYiShaoNian.txt";
    JavaIO.readFileByBytes(filename);
    JavaIO.readFileByChar(filename);
    JavaIO.readFileByLine(filename);
    JavaIO.readFileByRandomAccess(filename);
  }
}

Java写文件

package 天才白痴梦;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;

public class JavaIO2 {

  public static void main(String[] args) throws IOException {
    String Path="E:\\天才白痴梦\\JAVA";
    File file=new File("E:\\天才白痴梦\\JAVA","BaiYiShaoNian.txt");
    if (!file.exists()) {
      try {
        file.createNewFile();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    /**
     * Java写入文件的三种方法
     * */
    FileOutputStream fos=null;
    BufferedWriter bw=null;
    FileWriter fw=null;
    int value=1000;
    
    try {
      fos=new FileOutputStream(new File(Path+"fos.txt"));
      long begin=System.currentTimeMillis();
      for (int i=1; i<=value; i++) {
        fos.write(5);
      }
      long end=System.currentTimeMillis();
      System.out.println("TheCostTime of FileOutputStream is : " + (end-begin));
      fos.close();
      
      bw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(Path+"br.txt")),"UTF8"));
      begin=System.currentTimeMillis();
      for (int i=1; i<=value; i++) {
        bw.write(5);
        bw.newLine();
      }
      bw.close();
      end=System.currentTimeMillis();
      System.out.println("TheCostTime of BufferedWriter is : " + (end-begin));
      
      fw=new FileWriter(Path+"fw.txt");
      begin=System.currentTimeMillis();
      for (int i=1; i<=value; i++) {
        fw.write(5);        
      }
      fw.close();
      end=System.currentTimeMillis();
      System.out.println("TheCostTime of FileWriter is : " + (end-begin));
      
      
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } finally {
      try {
        fos.close(); //FileOutputStream
        bw.close(); //BufferedWriter
        fw.close(); //FileWriter
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    
  }
}

以上这篇Java读写文件方法总结(推荐)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • java数据结构和算法中数组的简单入门

    java数据结构和算法中数组的简单入门

    在本文里小编给大家整理了关于java数据结构和算法中数组的简单入门知识点整理,需要的朋友们学习下。
    2019-06-06
  • 关于Linux服务器配置java环境遇到的问题小结

    关于Linux服务器配置java环境遇到的问题小结

    这篇文章主要介绍了关于Linux服务器配置java环境遇到的问题小结,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-12-12
  • Springboot application.yml配置文件拆分方式

    Springboot application.yml配置文件拆分方式

    这篇文章主要介绍了Springboot application.yml配置文件拆分方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-05-05
  • SpringMvc接受请求参数的几种情况演示

    SpringMvc接受请求参数的几种情况演示

    Springmvc接受请求参数的几种介绍,如何接受json请求参数,本文通过实例代码给大家介绍的非常详细,需要的朋友参考下吧
    2021-07-07
  • SpringBoot Redis 发布订阅模式(Pub/Sub)的具体使用

    SpringBoot Redis 发布订阅模式(Pub/Sub)的具体使用

    本文主要介绍了SpringBoot Redis 发布订阅模式(Pub/Sub)的具体使用,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-12-12
  • Springboot @RequestBody注解踩坑记录

    Springboot @RequestBody注解踩坑记录

    这篇文章主要介绍了Springboot @RequestBody注解踩坑记录,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-03-03
  • RocketMQ设计之故障规避机制

    RocketMQ设计之故障规避机制

    这篇文章主要介绍了RocketMQ设计之故障规避机制,故障规避机制就是用来解决当Broker出现故障,Producer不能及时感知而导致消息发送失败的问题,下面详细介绍需要的小伙伴可以参考一下
    2022-03-03
  • Spring5中的WebClient使用方法详解

    Spring5中的WebClient使用方法详解

    这篇文章主要给大家介绍了关于Spring5中WebClient使用方法的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用Spring5具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
    2019-11-11
  • SpringSecurity默认登录页的使用示例教程

    SpringSecurity默认登录页的使用示例教程

    Spring 是非常流行和成功的 Java 应用开发框架,Spring Security 正是 Spring 家族中的成员,Spring Security 基于 Spring 框架,提供了一套 Web 应用安全性的完整解决方案,本文给大家介绍SpringSecurity的默认登录页的使用教程,感兴趣的朋友一起看看吧
    2023-12-12
  • Java超详细分析讲解final关键字的用法

    Java超详细分析讲解final关键字的用法

    关于final关键字,它也是我们一个经常用的关键字,可以修饰在类上、或者修饰在变量、方法上,以此看来定义它的一些不可变性!像我们经常使用的String类中,它便是final来修饰的类,并且它的字符数组也是被final所修饰的。但是一些final的一些细节你真的了解过吗
    2022-06-06

最新评论