gpt4 book ai didi

java - 使用java FileChannel复制文件并附加文件末尾,但终端卡住

转载 作者:太空宇宙 更新时间:2023-11-04 10:13:19 25 4
gpt4 key购买 nike

这是我的代码:

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”,它就会卡住。

它在Windows上运行并且没问题。

任何帮助将不胜感激。

最佳答案

最终解决方案:

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();
}
}

关于java - 使用java FileChannel复制文件并附加文件末尾,但终端卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52051586/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com