자바 가 파일 을 읽 는 몇 가지 방식

3581 단어 자바study
package myday01;

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 ReadFromFile {
	
	public static void main(String[] args){
		String fileName = "c:/logs/ecp.log";
		//readFileByRandomAccess(fileName);
		//readFileByLines(fileName);
		//readFileByChars(fileName);
		readFileByBytes(fileName);
	}
	/**
	 *         
	 */
	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>100)?50: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 (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	/**
	 *          ,             
	 */
	public static void readFileByLines(String fileName){
		BufferedReader reader =null;
		try{
			System.out.println("         ,      !");
			reader = new BufferedReader(new FileReader(fileName));
			String tempString = null;
			int line = 1;
			//     ,    null     
			while((tempString = reader.readLine())!=null){
				//    
				System.out.println("line " + line + ":" + tempString);
				line++;
			}
			reader.close();
		}catch (Exception e) {
			e.printStackTrace();// TODO: handle exception
		}finally {
			if(reader!=null){
				try{
					reader.close();
				}catch (Exception e) {
					e.printStackTrace();// TODO: handele exception
				}
			}
		}
	}
	
	/**
	 *           ,     、        
	 */
	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,  
. if(((char)tempChar)!='\r'){ System.out.print((char)tempChar); } } } catch (Exception e) { e.printStackTrace();// TODO: handle exception } */ try{ System.out.println("
, "); char[] tempChars = new char[100]; int charRead = 0; reader = new InputStreamReader(new FileInputStream(file)); // ,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

좋은 웹페이지 즐겨찾기