[英]using java FileChannel copy file and append the end of file, but the terminal stuck
這是我的代碼:
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class TestNIO {
public static void main(String[] args) throws IOException {
// in the file "hello world"
File file = new File("test.txt");
RandomAccessFile raf = new RandomAccessFile(file, "rws");
FileChannel fc = raf.getChannel();
ByteBuffer buffer = fc.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
fc.position(file.length());
fc.write(buffer);
fc.close();
raf.close();
}
}
我在終端的mac(jdk 8)上執行了它。 一旦執行“ java TestNIO”,它就會卡住。
它在Window上運行,可以。
任何幫助將不勝感激。
最終解決方案:
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
public class TestNIO3 {
public static void main(String[] args) throws IOException {
// in the file "hello world"
File file = new File("test.txt");
RandomAccessFile raf = new RandomAccessFile(file, "rw");
FileChannel fc = raf.getChannel();
ByteBuffer buffer = fc.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
fc.position(file.length());
Charset charset = Charset.defaultCharset();
CharsetDecoder decoder = charset.newDecoder();
CharBuffer cb = decoder.decode(buffer);
CharsetEncoder encoder = charset.newEncoder();
ByteBuffer to = encoder.encode(cb);
fc.write(to);
to.flip();
to.clear();
fc.close();
raf.close();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.