Skip to content

Instantly share code, notes, and snippets.

@jarek-przygodzki
Created December 6, 2012 21:24
Show Gist options
  • Save jarek-przygodzki/4228609 to your computer and use it in GitHub Desktop.
Save jarek-przygodzki/4228609 to your computer and use it in GitHub Desktop.
Truncate a file
import java.nio.channels.*
def truncFile(File file, long newSize) {
FileChannel fileChannel;
try {
fileChannel = new FileOutputStream(file, true).getChannel();
fileChannel.truncate(newSize);
} finally {
fileChannel?.close()
}
}
@messi18
Copy link

messi18 commented Jun 7, 2013

How about this:

def truncFile(File file, long newSize) {
new FileOutputStream(file).withStream{
it.channel.truncate(newSize)
}
}

@txiasummer
Copy link

Very elegant! Thank you both.

@vladistan
Copy link

Thanks. Great snippet.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment