Anonymous user
Truncate a file: Difference between revisions
+Java without throwing an error for a larger new size (cna be changed if that is really a hard requirement)
m (→{{header|PureBasic}}: Update) |
(+Java without throwing an error for a larger new size (cna be changed if that is really a hard requirement)) |
||
Line 1:
{{draft task}}
The task is to demonstrate how to truncate a file to a specific length. This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes). The truncation can be
=={{header|Java}}==
The built-in function for truncating a file in Java will leave the file unchanged if the specified size is larger than the file. This version expects the source file name and the new size as command line arguments (in that order).
<lang java>import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
public class TruncFile {
public static void main(String[] args) throws IOException{
if(args.length < 2){
System.out.println("Usage: java TruncFile fileName newSize");
return;
}
//turn on "append" so it doesn't clear the file
FileChannel outChan = new FileOutputStream(args[0], true).getChannel();
int newSize = Integer.parseInt(args[1]);
outChan.truncate(newSize);
outChan.close();
}
}</lang>
=={{header|PureBasic}}==
PureBasic has the internal function [http://www.purebasic.com/documentation/file/truncatefile.html TruncateFile] that cuts the file at the current file position and discards all data that follows.
|