001/* 002 * #%L 003 * Netarchivesuite - common 004 * %% 005 * Copyright (C) 2005 - 2014 The Royal Danish Library, the Danish State and University Library, 006 * the National Library of France and the Austrian National Library. 007 * %% 008 * This program is free software: you can redistribute it and/or modify 009 * it under the terms of the GNU Lesser General Public License as 010 * published by the Free Software Foundation, either version 2.1 of the 011 * License, or (at your option) any later version. 012 * 013 * This program is distributed in the hope that it will be useful, 014 * but WITHOUT ANY WARRANTY; without even the implied warranty of 015 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 016 * GNU General Lesser Public License for more details. 017 * 018 * You should have received a copy of the GNU General Lesser Public 019 * License along with this program. If not, see 020 * <http://www.gnu.org/licenses/lgpl-2.1.html>. 021 * #L% 022 */ 023 024package dk.netarkivet.common.tools; 025 026import java.io.File; 027import java.io.FileOutputStream; 028import java.io.IOException; 029import java.nio.ByteBuffer; 030import java.nio.channels.FileChannel; 031 032/** 033 * A class with a method for creating large files. Bruce Eckel's solution 034 * (http://www.java2s.com/ExampleCode/File-Input-Output/Creatingaverylargefileusingmapping.htm) is slightly slower! 035 */ 036public class WriteBytesToFile { 037 /** 038 * Writes a large number of bytes to a given file. 039 * 040 * @param args args[0] is the number of bytes to write args[1] the name of the output file 041 * @throws IOException If unable to write to output file 042 */ 043 public static void main(String[] args) throws IOException { 044 045 // A reasonably optimal value for the chunksize 046 int byteChunkSize = 10000000; 047 048 long nbytes = 0; 049 if (args.length != 2) { 050 System.out.println("Usage: java WriteBytesToFile nbytes filename"); 051 System.exit(1); 052 } 053 try { 054 nbytes = Long.parseLong(args[0]); 055 } catch (Exception e) { 056 System.out.println("First argument must be a number"); 057 } 058 File outputFile = new File(args[1]); 059 byte[] byteArr = new byte[byteChunkSize]; 060 FileOutputStream os = new FileOutputStream(outputFile); 061 FileChannel chan = os.getChannel(); 062 for (int i = 0; i < nbytes / byteChunkSize; i++) { 063 chan.write(ByteBuffer.wrap(byteArr)); 064 } 065 os.close(); 066 chan.close(); 067 } 068}