一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

Java文件读写的一些方法总结

时间:2013-01-24 编辑:简简单单 来源:一聚教程网

文件读写有以下几种常用的方法

1、字节读写(InputStream/OutputStream)、字符读取(FileReader/FileWriter)

FileInputStream的read(buffer)方法,每次从源程序文件OpenFile.java中读取512个字节,存储在缓冲区buffer中,再将以buffer中的值构造的字符串new String(buffer)显示在屏幕上。程序如下(本例程序放在包biz.1cn.stream里面,另外请在根目录下建立TestFile.txt文件,以便正常运行

 代码如下 复制代码

package biz.1cn.stream;
import java.io.FileInputStream;
import java.io.IOException;
/**
 * @author chenrz(simon)
 * @date 2006-6-29
 *      


 *       JAVA字节流例子-读文件
 *      


 */
public class ReadFile {
 public static void main(String[] args) {
     try {
  // 创建文件输入流对象
  FileInputStream is = new FileInputStream("TestFile.txt");
  // 设定读取的字节数
  int n = 512;
  byte buffer[] = new byte[n];
  // 读取输入流
  while ((is.read(buffer, 0, n) != -1) && (n > 0)) {
      System.out.print(new String(buffer));
  }
  System.out.println();
  // 关闭输入流
  is.close();
     } catch (IOException ioe) {
  System.out.println(ioe);
     } catch (Exception e) {
  System.out.println(e);
     }
 }
}

本例用System.in.read(buffer)从键盘输入一行字符,存储在缓冲区buffer中,再以FileOutStream的write(buffer)方法,将buffer中内容写入文件WriteFile.txt中,程序如下(本例程序放在包biz.1cn.stream里面,另外运行后会在根目录下建立WriteFile.txt文件):

 代码如下 复制代码

package biz.1cn.stream;
import java.io.FileOutputStream;
import java.io.IOException;
/**
 * @author chenrz(simon)
 * @date 2006-6-29
 *      


 *       JAVA字节流例子-写文件(www.1cn.biz)
 *      


 */
public class WriteFile {
 public static void main(String[] args) {
     try {
  System.out.print("输入要保存文件的内容:");
  int count, n = 512;
  byte buffer[] = new byte[n];
  // 读取标准输入流
  count = System.in.read(buffer);
  // 创建文件输出流对象
  FileOutputStream os = new FileOutputStream("WriteFile.txt");
  // 写入输出流
  os.write(buffer, 0, count);
  // 关闭输出流
  os.close();
  System.out.println("已保存到WriteFile.txt!");
     } catch (IOException ioe) {
  System.out.println(ioe);
     } catch (Exception e) {
  System.out.println(e);
     }
 }
}

2、字符读取(FileReader/FileWriter)

 代码如下 复制代码

package test;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class Test {

public static void main(String arg[]) {
  String fileName = "E:sharetest.txt";
  String writeData = "HelloWorld!rnnihao我的内存是3G的 ";
  File file = new File(fileName);
  if(file.exists()){
   file.delete();
  }
 
  char[] byteOutData = writeData.toCharArray();
  char[] byteInData = new char[50];
  int length = 0;
 
  try {
   file.createNewFile();
   if(file.exists() && file.canWrite()){
    FileWriter fileWrite = new FileWriter(file);
    fileWrite.write(byteOutData);
    fileWrite.close();
   }
   if (file.exists() && file.canRead()) {
    FileReader fileReader = new FileReader(file);
    while((length = fileReader.read(byteInData)) !=-1){
     System.out.print(new String(byteInData,0,length));
    }

     fileReader.close();
   }

  } catch (IOException e) {
   System.out.println("IOException occur");
   e.getMessage();
  }
}
}


3、行读取(BufferedReader/BufferedWriter)


代码(以读取为例):

 代码如下 复制代码


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
/**
 * 文件读取类

 * 1、按字节读取文件内容

 * 2、按字符读取文件内容

 * 3、按行读取文件内容

 * @author qin_xijuan
 *
 */
public class FileOperate {
   
    private static final String FILE_PATH = "d:/work/the List of Beautiful Music.txt";

    /**
     * 以字节为单位读取文件内容
     * @param filePath:需要读取的文件路径
     */
    public static void readFileByByte(String filePath) {
        File file = new File(filePath);
        // InputStream:此抽象类是表示字节输入流的所有类的超类。
        InputStream ins = null ;
        try{
            // FileInputStream:从文件系统中的某个文件中获得输入字节。
            ins = new FileInputStream(file);
            int temp ;
            // read():从输入流中读取数据的下一个字节。
            while((temp = ins.read())!=-1){
                System.out.write(temp);
            }
        }catch(Exception e){
            e.getStackTrace();
        }finally{
            if (ins != null){
                try{
                    ins.close();
                }catch(IOException e){
                    e.getStackTrace();
                }
            }
        }
    }
   
    /**
     * 以字符为单位读取文件内容
     * @param filePath
     */
    public static void readFileByCharacter(String filePath){
        File file = new File(filePath);
        // FileReader:用来读取字符文件的便捷类。
        FileReader reader = null;
        try{
            reader = new FileReader(file);
            int temp ;
            while((temp = reader.read()) != -1){
                if (((char) temp) != 'r') {
                    System.out.print((char) temp);
                }
            }
        }catch(IOException e){
            e.getStackTrace();
        }finally{
            if (reader != null){
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
   
    /**
     * 以行为单位读取文件内容
     * @param filePath
     */
    public static void readFileByLine(String filePath){
        File file = new File(filePath);
        // BufferedReader:从字符输入流中读取文本,缓冲各个字符,从而实现字符、数组和行的高效读取。
        BufferedReader buf = null;
        try{
            // FileReader:用来读取字符文件的便捷类。
            buf = new BufferedReader(new FileReader(file));
            // buf = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
            String temp = null ;
            while ((temp = buf.readLine()) != null ){
                System.out.println(temp);
            }
        }catch(Exception e){
            e.getStackTrace();
        }finally{
            if(buf != null){
                try{
                    buf.close();
                } catch (IOException e) {
                    e.getStackTrace();
                }
            }
        }
    }

    public static void main(String args[]) {
        readFileByByte(FILE_PATH);
        readFileByCharacter(FILE_PATH);
        readFileByLine(FILE_PATH);
    }
}

热门栏目