Created
March 28, 2017 07:42
-
-
Save qingniufly/f985e45664e17c355a2bd9ea79c74250 to your computer and use it in GitHub Desktop.
Java NIO file ops
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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