//给你改了一下,把读的循环去掉就行了
import java.io.*;
import java.nio.*;
import java.nio.channels.FileChannel;public class FileRWTest
{
  public static void main(String[]str)
  {
    String str1 = "I love you miss you";
    File txtFile = new File("txtTestFile.txt");
    ByteBuffer buf = ByteBuffer.allocate(100);
        FileOutputStream outFile = null;
    FileInputStream inFile = null;
    try
    {
      txtFile.createNewFile();
      outFile = new FileOutputStream(txtFile);
      inFile = new FileInputStream(txtFile);
    }
    catch (FileNotFoundException e)
    {
      e.printStackTrace(System.err);
    }
    catch (IOException e)
    {
      e.printStackTrace(System.err);
    }
    FileChannel outChannel = outFile.getChannel();
    FileChannel inChannel = inFile.getChannel();
    buf.put(str1.getBytes());
    buf.flip();
    try
    {
      outChannel.write(buf);
      buf.clear();
      outFile.close();
    }
    catch (IOException e)
    {
      e.printStackTrace(System.err);
      System.exit(0);
    }    try
    {
      inChannel.read(buf);
      System.out.println(" the test " +(((ByteBuffer)buf.flip()).asCharBuffer().toString()));
      buf.clear();
      
      System.out.println("EOF reached");
      inFile.close();
    }
    catch (IOException e)
    {
      e.printStackTrace(System.err);
      System.exit(0);
    }
  }
}

解决方案 »

  1.   

    怎么会不行,我都试过了,没有问题的.你把原来的.class和.txt文件删除,把上边的代码粘过去重新编译一下试试.
      

  2.   

    好,我试了后,还是那样(Dos下的JDK)不知为什么?在Jbuilder中编译也是一样的。
      

  3.   

    你用的是英文操作系统吧?那默认字符集不是GBK了。还有我用JDK1.4.2和JDK1.5都是这样的显示:
    the test ?汯癥?潵?楳猠祯
    EOF reached
      

  4.   

    说明你要做的事情,或许有更好的写法呢。
    如果你要读肉眼能看懂的文件,就应该用BufferedReader,写文件就应该用PrintWriter
      

  5.   

    你试一试 locale 设置一下区域.
      

  6.   

    回:funcreal,
       我要做的就是把一个字符串写到文件(txtTestFile.txt),然后把他又读出来.
       PrintWriter一般是格式二进制数据..BufferReader只不过是缓冲Reader类的子类的.而Reader类发险象环生不能用于读文件.
       
    望高手们看看,问题出在那里,如果有更好解决方法,或不同的方法.给我指点一下.
      

  7.   

    试试System.out.println(" the test " + new String(buf.array()));
      

  8.   

    当然可以去掉空格new String(buf.array()).trim()
      

  9.   

    回Fanly,能不能分析一下,为什么,成功了,感谢,怎么给你加分.
      

  10.   

    buf.array()得到buf的byte数组,再取它的内容就可以了
      

  11.   

    但是AsCharbuffer,为什么不行呢?
      

  12.   

    asCharBuffer()反而变成CharBuffer了
      

  13.   

    buf.flip()返回的是Buffer类型,可以强行转换为:ByteBuffer.为什么不能转换为:CharBuffer
      

  14.   

    不知那们高手可以看出来asCharBuffer()
    为什么是筹码的原因?