3 เม.ย. 2556

Java Read File


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
 
public class ReadFiles {
    public static void main(String[] args) throws IOException {
        ReadFiles re = new ReadFiles();
        long a = System.currentTimeMillis();
        System.out.println("Start");
        for (int i = 0; i < 10000; i++) {
            String data = re.readFileChannel("test.txt");     
        }
        System.out.println("Finish "+(System.currentTimeMillis()-a)+" Millsec");
    }
    public String readFile(String fileName) throws IOException {
           File f = new File(fileName);
           FileInputStream fstream = new FileInputStream(f);
           byte[] bytes = new byte[(int) f.length()];
           fstream.read(bytes);
           fstream.close();
           return new String(bytes);
        }
    public String readFileBuffer(String fileName) throws IOException{
        FileInputStream in = new FileInputStream(new File(fileName));
        BufferedReader re = new BufferedReader(new InputStreamReader(in));
        String line = "";
        StringBuffer buf = new StringBuffer();
        while((line=re.readLine())!=null){
            buf.append(line+"\n");
        }
        return buf.toString();
    }
    public String readFileChannel(String file) throws IOException {
           FileChannel channel = new FileInputStream(new File(file)).getChannel();
           ByteBuffer buffer = ByteBuffer.allocate((int) channel.size());
           channel.read(buffer);
           channel.close();
           return new String(buffer.array());
        }
}

ไม่มีความคิดเห็น:

แสดงความคิดเห็น