Skip to content

Instantly share code, notes, and snippets.

@qingniufly
Created March 28, 2017 07:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save qingniufly/f985e45664e17c355a2bd9ea79c74250 to your computer and use it in GitHub Desktop.
Save qingniufly/f985e45664e17c355a2bd9ea79c74250 to your computer and use it in GitHub Desktop.
Java NIO file ops
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class CopyFile {
public static void main(String[] args) {
String infname = "/tmp/in.txt";
String outfname = "/tmp/out.txt";
FileInputStream fis = new FileInputStream(infname);
FileOutputStream fos = new FileOutputStream(outfname);
FileChannel fcin = fis.getChannel();
FileChannel fcout = fos.getChannel();
ByteBuffer buff = ByteBuffer.allocate(1024);
while(true) {
// read mode(from channel to buffer);
// set position to 0, limit to capacity;
buff.clear();
int n = fcin.read(buff);
if (n == -1) {
break;
} else {
// write mode(from buffer to channel);
// set limit to position, position to 0;
buff.flip();
fcout.write(buff);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment