有两点,一是你并没有真正的把文件读进去,下面黑体部分是我修改之后的;二是你没有把文件的内容写进source中,这个你自己修改一下或者我稍后改一下吧
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
import java.io.*;
public class ChangeBuffer {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
// String data = "friends.dat";
File data =new File("D:\\friends.dat");
FileInputStream inData = new FileInputStream(data);
FileChannel inChannel = inData.getChannel();
long inSize = inChannel.size();
//show the size of the file in terms of byte
System.out.println("The size of the channel is " + inSize + ".");
ByteBuffer source = ByteBuffer.allocate( (int)inSize );
inChannel.read(source, 0);
System.out.println("The original data is: ");
while(source.remaining() > 0)
System.out.print(source.get() + " ");
//---------------------------------------------------------------------------
} catch (FileNotFoundException fne) {
System.out.println(fne.getMessage());
} catch (IOException ioe) {
System.out.println(ioe.getMessage());
}
}
}
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
import java.io.*;
public class ChangeBuffer {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
// String data = "friends.dat";
File data =new File("D:\\friends.dat");
FileInputStream inData = new FileInputStream(data);
FileChannel inChannel = inData.getChannel();
long inSize = inChannel.size();
//show the size of the file in terms of byte
System.out.println("The size of the channel is " + inSize + ".");
ByteBuffer source = ByteBuffer.allocate( (int)inSize );
inChannel.read(source, 0);
System.out.println("The original data is: ");
while(source.remaining() > 0)
System.out.print(source.get() + " ");
//---------------------------------------------------------------------------
} catch (FileNotFoundException fne) {
System.out.println(fne.getMessage());
} catch (IOException ioe) {
System.out.println(ioe.getMessage());
}
}
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货