[Java]读取文件方法大全

 [Java]读取文件方法大全

 

package com.qgmobile.testfile;

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

/**
 * 四种方式读取文件
 * 1、按字节读取文件内容
 *2、按字符读取文件内容
 *3、按行读取文件内容
 *4、随机读取文件内容
 * @author yangchuxi
 *
 */
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 readbyte=0;
     while((readbyte=in.read())!=-1){
      System.out.println("readbyte=="+readbyte);
     }
    }catch (IOException e) {
          e.printStackTrace();
    }finally{
     if(in!=null){
      try {
    in.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
     }
    }
    try{
     System.out.println("按字节读取文件内容,多个字节的读");
     in =new FileInputStream(file);
     byte[] tempbyte=new byte[30];
     int tempnum=0;
     while((tempnum=in.read(tempbyte))!=-1){
      System.out.println(tempbyte.toString());
     }
    }catch (IOException e) {
   e.printStackTrace();
    }finally{
     if(in!=null){
      try {
    in.close();
   } catch (IOException e) {
    e.printStackTrace();
    }
     }
    }
   
   }
   /**
    * 按字符读取文件
    * @param filename
    */
   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=0;
  while((tempchar=reader.read())!=-1){
   // 对于windows下,\r\n这两个字符在一起时,表示一个换行。
            // 但如果这两个字符分开显示时,会换两次行。
            // 因此,屏蔽掉\r,或者屏蔽\n。否则,将会多出很多空行
   if((char)tempchar!='\r'){
    System.out.println((char)tempchar);
   }
  }
  
 } catch (IOException e) {
  e.printStackTrace();
 }finally{
  if(reader!=null){
   try {
    reader.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }
  try {
  System.out.println("按字符读写文件,多个字符的读");
  reader=new InputStreamReader(new FileInputStream(file));
  char[] tempchar=new char[30];
  int charnum=0;
  while((charnum=reader.read(tempchar))!=-1){
   if(charnum==tempchar.length && (tempchar[tempchar.length-1])!='\r'){
    System.out.println(tempchar);
   }else{
    for (int i = 0; i <charnum; i++) {
     if(tempchar[i]!='\r'){
      System.out.println(tempchar[i]);
     }
    }
   }
  }
 } catch (IOException e) {
       e.printStackTrace();
 }finally{
  if(reader!=null){
   try {
    reader.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }
   }
   /**
    * 一整行的读取
    * @param filename
    */
   public static void readFileByLines(String filename){
    File file=new File(filename);
    BufferedReader reader=null;
    try {
  System.out.println("按行读取字符,一次读整一行");
  reader=new BufferedReader(new InputStreamReader(new FileInputStream(file)));
  String temp=null;
  int line=1;
  while((temp=reader.readLine())!=null){
   System.out.println("line="+line+"temp="+temp);
   line++;
  }
 } catch (IOException e) {
  e.printStackTrace();
 }finally{
  if(reader!=null){
   try {
    reader.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }
   }
   /**
    * 随机读写问价
    * @param filename
    */
   public static void readFileByRandomAccess(String filename){
    File file=new File(filename);
    RandomAccessFile rand=null;
    try {
  System.out.println("随机读写一段程序");
  rand=new RandomAccessFile(file, "r");
  long filelength=rand.length();
  int beginindex=(filelength>4)? 4:0;
  rand.seek(beginindex);
  byte[] tempbytes=new byte[10];
  int readnum=0;
  while((readnum=rand.read(tempbytes))!=-1){
   System.out.write(tempbytes,0,readnum);
  }
 } catch (IOException e) {
  e.printStackTrace();
 }finally{
  if(rand!=null){
   try {
    rand.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }
   }
   public static void main(String[] args) {
  String filename="resources.xml";
  readFileByBytes(filename);
  readFileByChars(filename);
  readFileByLines(filename);
  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);
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值