繁体   English   中英

使用java FileChannel复制文件并追加文件末尾,但是终端卡住了

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM