Java 调用RandomAccessFile实例的setLength方法时出现无效参数错误

Java 调用RandomAccessFile实例的setLength方法时出现无效参数错误,java,Java,代码如下: package vu.co.kaiyin; import java.io.FileOutputStream; import java.io.RandomAccessFile; import java.io.*; /** * Created by IDEA on 14/06/15. */ public class Test { public static void truncateFromEnd(File filename, int n) throws Exce

代码如下:

package vu.co.kaiyin;

import java.io.FileOutputStream;
import java.io.RandomAccessFile;



import java.io.*;

/**
 * Created by IDEA on 14/06/15.
 */
public class Test {

    public static void truncateFromEnd(File filename, int n) throws Exception {
        if(n < 0) {
            throw new Exception("Can't truncate by a negative number");
        }
        try (RandomAccessFile raf = new RandomAccessFile(filename, "r")) {
            long originalLength = raf.length();
            long newLength = originalLength - (long) n;
            if(newLength < 0) {
                newLength = 0;
            }
            raf.setLength(newLength);
        }
    }

    public static void truncateFromEnd(String filename, int n) throws Exception {
        truncateFromEnd(new File(filename), n);
    }

    public static void main(String[] args) throws Exception {
        FileOutputStream fo = new FileOutputStream("/tmp/bin.out");
        byte[] data = new byte[] {1, 2, 3, 4, 5};
        fo.write(data);
        fo.close();
        truncateFromEnd("/tmp/bin.out", 1);
    }
}

我做错了什么吗?

您可能需要通过在构造函数中传递
rw
(读/写)来授予您的
RandomAccessFile
写权限

try (RandomAccessFile raf = new RandomAccessFile(filename, "rw"))

如果您正在更改文件长度,那么您肯定是在写入文件。

您在哪个O/S上运行此操作?您是否验证了
/tmp
目录存在且可写?在OSX上运行时,/tmp是可写的,/tmp/bin.out实际上在那里,并且所有字节(从01到05)都是正确的。
try (RandomAccessFile raf = new RandomAccessFile(filename, "rw"))