Java实现按行读取大文件
String file = "F:" + File.separator + "a.txt";
FileInputStream fis = new FileInputStream(file);
RandomAccessFile raf = new RandomAccessFile(new File(file),"r");
String s ;
while((s =raf.readLine())!=null){
System.out.println(s);
}
raf.close();
fis.close();
网上流行的那个俩while版本不靠谱
可考虑bufferedinputstream和bufferedoutputstream来字节读取,这个代码太简单了,适用于非频繁操作。或采用nio的FileChannel,比较适合于高并发操作,如下为filechannel的部分代码
File inFile = new File("D:\\error");
File outFile = new File("D:\\to.txt");
FileChannel inFileChannel = new FileInputStream(inFile).getChannel();
FileChannel outFileChannel = new FileOutputStream(outFile).getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
while(-1 != inFileChannel.read(buffer)){
buffer.flip();
outFileChannel.write(buffer);
buffer.clear();
}
outFileChannel.close();
inFileChannel.close();
随机读取文件内容
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 tempbyte;
while ((tempbyte = in.read()) != -1) {
System.out.write(tempbyte);
}
in.close();
} catch (IOException e) {
e.print