非频繁操作如下:
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();
可考虑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();