NIO2提供两种主要的文件读取方法:
使用buffer和channel类
使用Path 和 File 类
NIO读取文件有以下三种方式:
1. 旧的NIO方式,使用BufferedReader
import java.io.BufferedReader
import java.io.FileReader
import java.io.IOException
public class WithoutNIOExample
{
public static void main(String[] args)
{
BufferedReader br = null
String sCurrentLine = null
try
{
br = new BufferedReader(
new FileReader("test.txt"))
while ((sCurrentLine = br.readLine()) != null)
{
System.out.println(sCurrentLine)
}
}
catch (IOException e)
{
e.printStackTrace()
}
finally
{
try
{
if (br != null)
br.close()
} catch (IOException ex)
{
ex.printStackTrace()
}
}
}
}
2. 使用buffer读取小文件
import java.io.IOException
import java.io.RandomAccessFile
import java.nio.ByteBuffer
import java.nio.channels.FileChannel
public class ReadFileWithFileSizeBuffer
{
public static void main(String args[])
{
try
{
RandomAccessFile aFile = new RandomAccessFile(
"test.txt","r")
FileChannel inChannel = aFile.getChannel()
long fileSize = inChannel.size()
ByteBuffer buffer = ByteBuffer.allocate((int) fileSize)
inChannel.read(buffer)
buffer.rewind()
buffer.flip()
for (int i = 0i <fileSizei++)
{
System.out.print((char) buffer.get())
}
inChannel.close()
aFile.close()
}
catch (IOException exc)
{
System.out.println(exc)
System.exit(1)
}
}
}
3. 分块读取大文件
import java.io.IOException
import java.io.RandomAccessFile
import java.nio.ByteBuffer
import java.nio.channels.FileChannel
public class ReadFileWithFixedSizeBuffer
{
public static void main(String[] args) throws IOException
{
RandomAccessFile aFile = new RandomAccessFile
("test.txt", "r")
FileChannel inChannel = aFile.getChannel()
ByteBuffer buffer = ByteBuffer.allocate(1024)
while(inChannel.read(buffer) >0)
{
buffer.flip()
for (int i = 0i <buffer.limit()i++)
{
System.out.print((char) buffer.get())
}
buffer.clear()// do something with the data and clear/compact it.
}
inChannel.close()
aFile.close()
}
}
4. 使用MappedByteBuffer读取文件
import java.io.RandomAccessFile
import java.nio.MappedByteBuffer
import java.nio.channels.FileChannel
public class ReadFileWithMappedByteBuffer
{
public static void main(String[] args) throws IOException
{
RandomAccessFile aFile = new RandomAccessFile
("test.txt", "r")
FileChannel inChannel = aFile.getChannel()
MappedByteBuffer buffer = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, inChannel.size())
buffer.load()?
for (int i = 0i <buffer.limit()i++)
{
System.out.print((char) buffer.get())
}
buffer.clear()// do something with the data and clear/compact it.
inChannel.close()
aFile.close()
}
}
OOM 说你的程序内存溢出了
你这个文件如果很大的话,建议用inputStreamReader
这个包装类,可以用指定的编码去读取文件
用法:
File file = new File("文件路径")
InputStreamReader isr = new InputStreamReader(new FileInputStream(file),"GBK")
更详细的用法,建议查看api
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)