问题描述
importjava.nio.*;importjava.nio.channels.*;importjava.nio.charset.*;importjava.io.*;publicclassChangeBuffer{publicstaticvoidmain(String[]args){//TODOAuto-generatedmethodstubtry{Stringdata="friends.dat";FileInputStreaminData=newFileInputStream(data);FileChannelinChannel=inData.getChannel();longinSize=inChannel.size();//showthesizeofthefileintermsofbyteSystem.out.println("Thesizeofthechannelis"+inSize+".");ByteBuffersource=ByteBuffer.allocate((int)inSize);inChannel.read(source,0);System.out.println("Theoriginaldatais:");while(source.remaining()>0)System.out.print(source.get()+"");//---------------------------------------------------------------------------}catch(FileNotFoundExceptionfne){System.out.println(fne.getMessage());}catch(IOExceptionioe){System.out.println(ioe.getMessage());}}}
在以上这段程序里面,friends.dat里面的数据是“abcd”这四个字母,可是我认为这段程序应该输出“abcd”,可是为什么木有呢?谢谢大家!
解决方案
解决方案二:
自己往上顶一顶!
解决方案三:
有两点,一是你并没有真正的把文件读进去,下面黑体部分是我修改之后的;二是你没有把文件的内容写进source中,这个你自己修改一下或者我稍后改一下吧importjava.nio.*;importjava.nio.channels.*;importjava.nio.charset.*;importjava.io.*;publicclassChangeBuffer{publicstaticvoidmain(String[]args){//TODOAuto-generatedmethodstubtry{//Stringdata="friends.dat";Filedata=newFile("D:\friends.dat");FileInputStreaminData=newFileInputStream(data);FileChannelinChannel=inData.getChannel();longinSize=inChannel.size();//showthesizeofthefileintermsofbyteSystem.out.println("Thesizeofthechannelis"+inSize+".");ByteBuffersource=ByteBuffer.allocate((int)inSize);inChannel.read(source,0);System.out.println("Theoriginaldatais:");while(source.remaining()>0)System.out.print(source.get()+"");//---------------------------------------------------------------------------}catch(FileNotFoundExceptionfne){System.out.println(fne.getMessage());}catch(IOExceptionioe){System.out.println(ioe.getMessage());}}}