日期:2014-05-20  浏览次数:20650 次

一个基础问题,请帮我看一下。
基础的IO类代码,有2个方法的意思不太理解,大家帮忙解释下,谢谢(不用看代码)
Java code
import java.nio.*;
import java.nio.channels.*;
import java.io.*;

public class ChannelCopy {
  private static final int BSIZE = 1024;
  public static void main(String[] args) throws Exception {
    if(args.length != 2) {
      System.out.println("arguments: sourcefile destfile");
      System.exit(1);
    }
    FileChannel
      in = new FileInputStream(args[0]).getChannel(),
      out = new FileOutputStream(args[1]).getChannel();
    ByteBuffer buffer = ByteBuffer.allocate(BSIZE);
    while(in.read(buffer) != -1) {
      buffer.flip(); //JDK上说是反转,但是似乎不是我所理解的反转意思,原来是 abc flip()后变成 cba(这是我对反转的理解)
      out.write(buffer);
      buffer.clear();  // 这里调用clear()有什么意义?
    }
  }
}


2、还想问大家个问题。虽然我对IO类的代码基本能看懂(暂时看到的那些),但是特别容易忘,而且还搞不大清楚(又是InputStream、OutputStream、Read、Write、FileChannel、ByteBuffer乱七八糟一堆,而且继承层次也很到,很容易晕)。总觉得学了很容易忘,过两天变的跟没学一样,大家有什么好的建议吗?

------解决方案--------------------
buffer.flip(); //JDK上说是反转,但是似乎不是我所理解的反转意思,原来是 abc flip()后变成 cba(这是我对反转的理解)
================
你的理解是对字符串反转的理解
详细:
http://bbs.tarena.com.cn/viewthread.php?tid=125914
------解决方案--------------------
1.buffer.clear(); // 这里调用clear()有什么意义?
将buffer清空,可以使每次的while循环都可以直接写入文件中,
如果不调用的话,就有机会不是每次循环都可以及时写入文件。

2.顾名思义,InputStream就是输入流,通过它就可以读取数据,它是抽象类,其它的XXXInputStream都是继承它。
OutputStream就是输出流了,可以通过它来写入一些数据,也是抽象类,其他的输出流也是继承它。
Read就是阅读器,可以读取输入流的数据,反正你在用的时候,尽量去思考下,为什么这样写,就很容易熟悉和掌握啦

------解决方案--------------------
引用楼主 llm0528 的帖子:
基础的IO类代码,有2个方法的意思不太理解,大家帮忙解释下,谢谢(不用看代码)

Java codeimport java.nio.*;
import java.nio.channels.*;
import java.io.*;

public class ChannelCopy {
private static final int BSIZE = 1024;
public static void main(String[] args) throws Exception {
if(args.length != 2) {
System.out.println("arguments: sourcefile destfile");
System.exit(1…

------解决方案--------------------
我刚开始也有和楼主一样的感觉,但是有一次项目里用了很多读写文件的操作,正好那块是我负责,之后就记住了,总之就是多用!
------解决方案--------------------
Java code
flip
public final Buffer flip()Flips this buffer. The limit is set to the current position and then the position is set to zero. If the mark is defined then it is discarded.