【发布时间】:2019-11-30 16:04:14
【问题描述】:
我有 2 个简单的函数来编写一个 int 并从映射文件中读取它,但似乎其中一个函数是错误的。
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Random;
public class MemoryMappedFileInJava {
// file
File file;
// channel to connect the file content to buffer
FileChannel channel;
// buffer
MappedByteBuffer buffer;
// buffer max size in bytes
final int BUFFER_MAX = 32;
@SuppressWarnings("resource")
MemoryMappedFileInJava() {
file = new File("file.txt");
//create a channel to write and read
try {
channel = new RandomAccessFile(file, "rw").getChannel();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// map the file content to buffer
try {
buffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, BUFFER_MAX);
} catch (IOException e) {
e.printStackTrace();
}
}
// read the value from buffer
int readInt() {
int number=0;
int c = buffer.getInt();
buffer.position(0);
while (c != '\0')
number += c;
return number;
}
// send the message to buffer
void writeInt(int number) {
buffer.position(0);
buffer.putInt(number);
buffer.putChar('\0');
}
// close the channel
void closeChannel() {
try {
channel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//lets make some tests with random numbers
static void run() {
Random r = new Random();
MemoryMappedFileInJava communication = new MemoryMappedFileInJava();
int number = r.nextInt(5) + 1;
communication.writeInt(number);
String prefix = "the given number from buffer is --> ";
System.out.print(prefix + communication.readInt());
}
public static void main(String[]args)
{
run();
}
}
我用来运行此代码的完整代码也可以从这里编译和运行: http://tpcg.io/5hOPVh1Q
输出打印总是给出 0,如果是在写入函数或读取函数中,我无法找到问题所在。
【问题讨论】:
-
我怀疑这段代码能给你带来什么,因为由于主要的语法和编译错误,它无法运行。请发布您正在编译和运行的实际代码。
-
@MarcoR。添加了我用来运行此代码的完整代码的链接:tpcg.io/5hOPVh1Q
-
你的问题必须是完整的。会员不会在互联网上寻找您问题的详细信息;所以编辑你的问题并在这里发布源代码。问题的任何非必要细节都可以在此处找到重要细节后链接。
-
@MarcoR。你是对的,我已经更新了我的问题帖子中的代码。
-
去掉处理NUL字符的部分。它们不是必需的,其中一些没有任何意义。实际上你甚至不需要这些方法:直接调用
getInt()和putInt()。我也不明白你为什么打电话给buffer.position(0)。真的只有一个数字吗?在文件的开头?注意这些是二进制数,不应写入名为 .txt 的文件。