从特定位置开始将文件复制到另一个文件

Copy a file into an other starting from a specific position

我有以下超过确定大小的文件,我想减少它,但我对文件的最后几行感兴趣,所以我想删除第一行,直到大小等于允许的大小,

在 java 中是否可以执行此操作?

试试这个:

long MAX_FILE_SIZE = 512;

try(RandomAccessFile file = new RandomAccessFile("Path to inputfile", "r"))
{
    long fileSize = file.length();

    long readStartPosition = fileSize - MAX_FILE_SIZE;
    if(readStartPosition < 0)
    {
        readStartPosition = 0;
    }

    file.seek(readStartPosition);

    try(OutputStream outputStream = new BufferedOutputStream(new FileOutputStream("Path to outputfile")))
    {
        byte[] buffer = new byte[1024];
        for(int bytesRead = file.read(buffer); bytesRead != -1; bytesRead = file.read(buffer))
        {
            outputStream.write(buffer, 0, bytesRead);
        }
    }
}
catch(Throwable t)
{
    System.out.println(t);;
}

或者这个,如果你想保留同一个文件:

long MAX_FILE_SIZE = 512;

try(RandomAccessFile file = new RandomAccessFile("Path to inputfile", "rw"))
{
    long fileSize = file.length();

    long readStartPosition = fileSize - MAX_FILE_SIZE;
    if(readStartPosition < 0)
    {
        return;
    }

    long writePosition = 0;
    byte[] buffer = new byte[1024];

    file.seek(readStartPosition);
    for(int bytesRead = file.read(buffer); bytesRead != -1; bytesRead = file.read(buffer))
    {
        long currentPosition = file.getFilePointer();

        file.seek(writePosition);
        file.write(buffer, 0, bytesRead);

        writePosition += bytesRead;

        file.seek(currentPosition);
    }

    long newSize = file.length() - readStartPosition;
    file.setLength(newSize);
}
catch(Throwable t)
{
    System.out.println(t);;
}

注意:这两个示例都写在我的头顶上,但它们应该有效。至少你掌握了窍门。