`
jaczhao
  • 浏览: 85809 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

java按行读文件并写文件

阅读更多
package ewanbao.mydomain.com;
 
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
 
public class ReadHugeFile {
 public static void main(String[] args) {
  /* check the argument */
  if(args.length != 2){
   System.out.println("java ewanbao.mydomain.com.ReadHugeFile" +
     " [Input File Name]" +
     " [Output File Name]");
   System.exit(0);
  }
  
  
  BufferedWriter writer = null;
  try{
   /* prepare the output */
   writer = new BufferedWriter(new FileWriter(args[1]));
   
   /* prepare the input */
   String strBuf = "";
   int bufsize = 1024;
   byte[] bs = new byte[bufsize];
   ByteBuffer byteBuf = ByteBuffer.allocate(bufsize);
   FileChannel channel = new RandomAccessFile(args[0], "r").getChannel();
   while(channel.read(byteBuf) != -1){
    /* read the content to byte array */
    int size = byteBuf.position();
    byteBuf.rewind();
    byteBuf.get(bs);
    byteBuf.clear();
    
    String tempString = new String(bs, 0, size);
    int fromIndex = 0;
    int endIndex = 0;
    while((endIndex = tempString.indexOf("/n", fromIndex)) != -1){
     String line = tempString.substring(fromIndex, endIndex);
     line = new String(strBuf + line);
     writer.write(line);
     writer.newLine();
     
     strBuf = "";
     fromIndex = endIndex + 1;
    }
    strBuf = tempString.substring(fromIndex, size);
   }
  }catch(Exception e){
   e.printStackTrace();
  }finally{
   if(writer != null){
    try{
     writer.close();
    }catch(Exception e){
     e.printStackTrace();
    }
   }
  }
 }
 
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics