Tag: randomaccessfile

从Java中的随机访问文件中读取

我正在尝试设置一个while循环,它将从RandomAccessFile读取并在到达文件末尾时停止。 但每次我尝试运行程序时都会出错。 RandomAccessFile raf = new RandomAccessFile(filename, “rw”); final int EOF = -1; while(raf.readInt() != EOF){ id = raf.readInt(); existingMileage = raf.readInt(); gasCost = raf.readInt(); ndays = raf.readInt(); rate = raf.readInt(); totalCharge = raf.readInt(); discount = raf.readInt(); tax = raf.readInt(); netCharge = raf.readInt(); returnMileage = raf.readInt(); } 这是我得到的错误: Exception in thread “main” java.io.EOFException at java.io.RandomAccessFile.readInt(Unknown […]

获取文本文件中行的字节偏移量?

我有一个文本文件 one two three four five 我需要获取文件中每一行的偏移量。 我如何用Java做到这一点? 我搜索了一些I / O库(如BufferedReader和RandomAccessFile),但我无法找到满意的答案。 任何人都可以建议如何处理这个?

在二进制流中搜索字符串(作为byte )

嗨团队,我试图在二进制文件中找到一个字符串“亨利”,并将字符串更改为不同的字符串。 FYI文件是对象序列化的输出。 原始问题在这里 我是新手搜索字节,想象这个代码会搜索我的byte []并交换它。 但它并没有接近工作它甚至找不到匹配。 { byte[] bytesHenry = new String(“Henry”).getBytes(); byte[] bytesSwap = new String(“Zsswd”).getBytes(); byte[] seekHenry = new byte[bytesHenry.length]; RandomAccessFile file = new RandomAccessFile(fileString,”rw”); long filePointer; while (seekHenry != null) { filePointer = file.getFilePointer(); file.readFully(seekHenry); if (bytesHenry == seekHenry) { file.seek(filePointer); file.write(bytesSwap); break; } } } 好的,我看到bytesHenry==seekHenry问题,并将交换到Arrays.equals( bytesHenry , seekHenry ) 我想每次读取5个字节时我需要移动-4个字节的位置。 […]

使用RandomAccessFile清除Java中的文件内容

我试图清除我在java中创建的文件的内容。 该文件由PrintWriter调用创建。 我在这里读到可以使用RandomAccessFile这样做,并在其他地方读取,这实际上比调用新的PrintWriter并立即关闭它以使用空白覆盖文件更好。 但是,使用RandomAccessFile不起作用,我不明白为什么。 这是我的代码的基本大纲。 PrintWriter writer = new PrintWriter(“temp”,”UTF-8″); while (condition) { writer.println(“Example text”); if (clearCondition) { new RandomAccessFile(“temp”,”rw”).setLength(0); // Although the solution in the link above did not include ‘,”rw”‘ // My compiler would not accept without a second parameter writer.println(“Text to be written onto the first line of temp file”); } } […]

java中的RandomAccessFile是否读取内存中的整个文件?

我需要读取一个大文件的最后n行(比如2GB)。 该文件是UTF-8编码的。 想知道最有效的方法。 在java中读取RandomAccessFile,但是seek()方法读取内存中的整个文件。 它使用本机实现,因此我无法引用源代码。