这是我的代码:
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上运行,并且可以。
任何帮助将不胜感激。
答案 0 :(得分:0)
最终解决方案:
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();
}
}