-1
我有一個大的文本文件,其中有數以千計的數字被空格分隔。我想用Java FileChannel讀取每個數字。Java:如何使用FileChannel從文件中讀取數字
我能夠使用這裏提到的第一種方法來讀取文件:http://howtodoinjava.com/2013/05/01/3-ways-to-read-files-using-java-nio/但我不知道我將如何讀取每個數字的兩個,三個和四個數字。
我的代碼:
public static void main(String args[]) {
try
{
String file_name="abc.txt";
RandomAccessFile input_file = new RandomAccessFile(file_name,"r");
FileInputStream in = new FileInputStream(file_name);
FileChannel ch = in.getChannel();
FileChannel inChannel = input_file.getChannel();
long file_size = inChannel.size();
ByteBuffer buffer = ByteBuffer.allocate((int) file_size);
Charset cs = Charset.forName("ASCII");
// inChannel.read(buffer);
int rd;
while ((rd = ch.read(buffer)) != -1)
{
buffer.rewind();
System.out.println("String read: ");
CharBuffer chbuf = cs.decode(buffer);
for (int i = 0; i < chbuf.length(); i++)
{
System.out.print(chbuf.get());
}
buffer.clear();
inChannel.close();
input_file.close();
}
}
catch (IOException exc){}
}}
你意味着使用nio的第一種方法?我甚至可以做到這一點。我得到一個java.nio.BufferUnderflowException。 –
我的意思是 1)讀取文件大小緩衝區中的小文件 其工作完美... –
您是否在任何時候都收到java.nio.BufferUnderflowException異常?你在這種情況下閱讀的文件是什麼樣的?你是否需要修改代碼? –