Example usage for java.io RandomAccessFile setLength

List of usage examples for java.io RandomAccessFile setLength

Introduction

In this page you can find the example usage for java.io RandomAccessFile setLength.

Prototype

public native void setLength(long newLength) throws IOException;

Source Link

Document

Sets the length of this file.

Usage

From source file:phex.util.FileUtils.java

/**
 * Appends the fileToAppend on the destination file. The file that is appended
 * will be removed afterwards.// w  w  w  .j a  va  2  s  .com
 *
 * @throws IOException in case an IO operation fails
 */
public static void appendFile(File destination, File fileToAppend) throws IOException {
    long destFileLength = destination.length();
    long appendFileLength = fileToAppend.length();
    // open files
    FileInputStream inStream = new FileInputStream(fileToAppend);
    try {
        RandomAccessFile destFile = new RandomAccessFile(destination, "rwd");
        try {
            // extend file length... this causes dramatical performance boost since
            // contents is streamed into already freed space.
            destFile.setLength(destFileLength + appendFileLength);
            destFile.seek(destFileLength);
            byte[] buffer = new byte[(int) Math.min(BUFFER_LENGTH, appendFileLength)];
            int length;
            while (-1 != (length = inStream.read(buffer))) {
                long start2 = System.currentTimeMillis();
                destFile.write(buffer, 0, length);
                long end2 = System.currentTimeMillis();
                try {
                    Thread.sleep((end2 - start2) * 2);
                } catch (InterruptedException exp) {
                    // reset interrupted flag
                    Thread.currentThread().interrupt();
                    return;
                }
            }
        } finally {
            destFile.close();
            IOUtil.closeQuietly(destFile);
        }
    } finally {
        IOUtil.closeQuietly(inStream);
    }

    FileUtils.deleteFileMultiFallback(fileToAppend);
}

From source file:io.milton.zsync.UploadReader.java

/**
 * Copies the contents of the source file to the destination file and sets
 * the destination file's length./*from  w w  w. j  a  v  a 2s  .c  om*/
 *
 * @param inFile The source file
 * @param outFile The destination file
 * @param length The desired length of the destination file
 * @throws IOException
 */
private static void copyFile(File inFile, File outFile, long length) throws IOException {

    InputStream fIn = null;
    OutputStream fOut = null;
    RandomAccessFile randAccess = null;

    try {

        fIn = new FileInputStream(inFile);
        fOut = new FileOutputStream(outFile);
        RangeUtils.sendBytes(fIn, fOut, inFile.length());
    } finally {
        StreamUtils.close(fIn);
        StreamUtils.close(fOut);
    }

    try {

        randAccess = new RandomAccessFile(outFile, "rw");
        randAccess.setLength(length);
    } finally {
        Util.close(randAccess);
    }
}

From source file:phex.util.FileUtils.java

/**
 * Splits the source file at the splitpoint into the destination file.
 * The result will be the source file containing data to the split point and
 * the destination file containing the data from the split point to the end
 * of the file.//from   w ww .  jav  a 2  s  . c  o m
 *
 * @param source      the source file to split.
 * @param destination the destination file to split into.
 * @param splitPoint  the split point byte position inside the file.
 *                    When the file size is 10 and the splitPoint is 3 the source file will contain
 *                    the first 3 bytes while the destination file will contain the last 7 bytes.
 * @throws IOException in case of a IOException during split operation.
 */
public static void splitFile(File source, File destination, long splitPoint) throws IOException {
    // open files
    RandomAccessFile sourceFile = new RandomAccessFile(source, "rws");
    try {
        FileOutputStream outStream = new FileOutputStream(destination);
        try {
            sourceFile.seek(splitPoint);
            byte[] buffer = new byte[(int) Math.min(BUFFER_LENGTH, source.length() + 1)];
            int length;
            while (-1 != (length = sourceFile.read(buffer))) {
                outStream.write(buffer, 0, length);
            }
            sourceFile.setLength(splitPoint);
        } finally {
            IOUtil.closeQuietly(outStream);
        }
    } finally {
        IOUtil.closeQuietly(sourceFile);
    }
}

From source file:Gen.java

public static void genWeb() throws Exception {

    String GEN_WEBINF = GEN_ROOT + FILE_SEPARATOR + "war" + FILE_SEPARATOR + "WEB-INF";

    String WAR_NAME = System.getProperty("warname") != null && !System.getProperty("warname").equals("")
            ? System.getProperty("warname")
            : MAPPING_JAR_NAME.substring(0, MAPPING_JAR_NAME.length() - "jar".length()) + "war";
    if (!WAR_NAME.endsWith(".war"))
        WAR_NAME += ".war";

    String PROPS_EMBED = System.getProperty("propsembed") != null
            && !System.getProperty("propsembed").equals("") ? System.getProperty("propsembed") : null;

    deleteDir(GEN_ROOT + FILE_SEPARATOR + "war");

    regenerateDir(GEN_WEBINF + FILE_SEPARATOR + "classes");
    regenerateDir(GEN_WEBINF + FILE_SEPARATOR + "lib");

    Vector<String> warJars = new Vector<String>();
    warJars.add(GEN_ROOT_LIB + FILE_SEPARATOR + MAPPING_JAR_NAME);

    InputStream inputStreamCore = Gen.class.getResourceAsStream("/biocep-core-tomcat.jar");
    if (inputStreamCore != null) {
        try {//w  ww  .ja v  a 2  s  .  c  o  m
            byte data[] = new byte[BUFFER_SIZE];
            FileOutputStream fos = new FileOutputStream(
                    GEN_WEBINF + FILE_SEPARATOR + "lib" + "/biocep-core.jar");
            int count = 0;
            while ((count = inputStreamCore.read(data, 0, BUFFER_SIZE)) != -1) {
                fos.write(data, 0, count);
            }
            fos.flush();
            fos.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {

        warJars.add("RJB.jar");

        warJars.add("lib/desktop/JRI.jar");

        FilenameFilter jarsFilter = new FilenameFilter() {
            public boolean accept(File arg0, String arg1) {
                return arg1.endsWith(".jar");
            }
        };

        {
            String[] derby_jdbc_jars = new File("lib/jdbc").list(jarsFilter);
            for (int i = 0; i < derby_jdbc_jars.length; ++i) {
                warJars.add("lib/jdbc" + FILE_SEPARATOR + derby_jdbc_jars[i]);
            }
        }

        {
            String[] pool_jars = new File("lib/pool").list(jarsFilter);
            for (int i = 0; i < pool_jars.length; ++i) {
                warJars.add("lib/pool" + FILE_SEPARATOR + pool_jars[i]);
            }
        }

        {
            String[] httpclient_jars = new File("lib/j2ee").list(jarsFilter);
            for (int i = 0; i < httpclient_jars.length; ++i) {
                warJars.add("lib/j2ee" + FILE_SEPARATOR + httpclient_jars[i]);
            }
        }
    }

    log.info(warJars);
    for (int i = 0; i < warJars.size(); ++i) {
        Copy copyTask = new Copy();
        copyTask.setProject(_project);
        copyTask.setTaskName("copy to war");
        copyTask.setTodir(new File(GEN_WEBINF + FILE_SEPARATOR + "lib"));
        copyTask.setFile(new File(warJars.elementAt(i)));
        copyTask.init();
        copyTask.execute();
    }

    unzip(Gen.class.getResourceAsStream("/jaxws.zip"), GEN_WEBINF + FILE_SEPARATOR + "lib",
            new EqualNameFilter("activation.jar", "jaxb-api.jar", "jaxb-impl.jar", "jaxb-xjc.jar",
                    "jaxws-api.jar", "jaxws-libs.jar", "jaxws-rt.jar", "jaxws-tools.jar", "jsr173_api.jar",
                    "jsr181-api.jar", "jsr250-api.jar", "saaj-api.jar", "saaj-impl.jar", "sjsxp.jar",
                    "FastInfoset.jar", "http.jar", "mysql-connector-java-5.1.0-bin.jar", "ojdbc-14.jar"),
            BUFFER_SIZE, false, "Unzipping psTools..", 17);

    PrintWriter pw_web_xml = new PrintWriter(GEN_WEBINF + FILE_SEPARATOR + "web.xml");
    pw_web_xml.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    pw_web_xml.println(
            "<web-app version=\"2.4\" xmlns=\"http://java.sun.com/xml/ns/j2ee\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd\">");
    pw_web_xml.println(
            "<listener><listener-class>com.sun.xml.ws.transport.http.servlet.WSServletContextListener</listener-class></listener>");

    for (String className : DirectJNI._rPackageInterfacesHash.keySet()) {
        String shortClassName = className.substring(className.lastIndexOf('.') + 1);
        pw_web_xml.println("<servlet><servlet-name>" + shortClassName
                + "_servlet</servlet-name><servlet-class>org.kchine.r.server.http.frontend.InterceptorServlet</servlet-class><load-on-startup>1</load-on-startup></servlet>");
    }

    pw_web_xml.println("<servlet><servlet-name>" + "WSServlet"
            + "</servlet-name><servlet-class>com.sun.xml.ws.transport.http.servlet.WSServlet</servlet-class><load-on-startup>1</load-on-startup></servlet>");

    pw_web_xml.println("<servlet><servlet-name>" + "MappingClassServlet"
            + "</servlet-name><servlet-class>org.kchine.r.server.http.frontend.MappingClassServlet</servlet-class><load-on-startup>1</load-on-startup></servlet>");

    for (String className : DirectJNI._rPackageInterfacesHash.keySet()) {
        String shortClassName = className.substring(className.lastIndexOf('.') + 1);
        pw_web_xml.println(
                "<servlet-mapping><servlet-name>" + shortClassName + "_servlet</servlet-name><url-pattern>/"
                        + shortClassName + "</url-pattern></servlet-mapping>");
    }

    pw_web_xml.println("<servlet-mapping><servlet-name>" + "MappingClassServlet"
            + "</servlet-name><url-pattern>" + "/mapping/classes/*" + "</url-pattern></servlet-mapping>");

    pw_web_xml.println("<session-config><session-timeout>30</session-timeout></session-config>");
    pw_web_xml.println("</web-app>");
    pw_web_xml.flush();
    pw_web_xml.close();

    PrintWriter pw_sun_jaxws_xml = new PrintWriter(GEN_WEBINF + FILE_SEPARATOR + "sun-jaxws.xml");
    pw_sun_jaxws_xml.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    pw_sun_jaxws_xml.println("<endpoints xmlns='http://java.sun.com/xml/ns/jax-ws/ri/runtime' version='2.0'>");

    for (String className : DirectJNI._rPackageInterfacesHash.keySet()) {
        String shortClassName = className.substring(className.lastIndexOf('.') + 1);
        pw_sun_jaxws_xml.println("   <endpoint    name='name_" + shortClassName + "'   implementation='"
                + className + "Web" + "' url-pattern='/" + shortClassName + "'/>");
    }

    pw_sun_jaxws_xml.println("</endpoints>");
    pw_sun_jaxws_xml.flush();
    pw_sun_jaxws_xml.close();

    if (PROPS_EMBED != null) {
        InputStream is = new FileInputStream(PROPS_EMBED);
        byte[] buffer = new byte[is.available()];
        is.read(buffer);
        RandomAccessFile raf = new RandomAccessFile(
                GEN_WEBINF + FILE_SEPARATOR + "classes" + FILE_SEPARATOR + "globals.properties", "rw");
        raf.setLength(0);
        raf.write(buffer);
        raf.close();
    }

    War warTask = new War();
    warTask.setProject(_project);
    warTask.setTaskName("war");
    warTask.setBasedir(new File(GEN_ROOT + FILE_SEPARATOR + "war"));
    warTask.setDestFile(new File(GEN_ROOT + FILE_SEPARATOR + WAR_NAME));
    warTask.setIncludes("**/*");
    warTask.init();
    warTask.execute();

}

From source file:com.adaptris.core.fs.CompositeFileFilterTest.java

private void write(long size, File f) throws IOException {
    RandomAccessFile rf = new RandomAccessFile(f, "rw");
    rf.setLength(size);
    rf.close();/*from w w  w . jav a  2  s. com*/
}

From source file:com.adaptris.core.fs.enhanced.FileSorterCase.java

private void ensureSize(long size, File f) throws IOException {
    RandomAccessFile rf = new RandomAccessFile(f, "rw");
    rf.setLength(size);
    rf.close();/*from   www .j av a  2 s  .  c  o  m*/
}

From source file:org.apache.servicecomb.demo.edge.business.Impl.java

protected File createBigFile() throws IOException {
    File file = new File(tempDir, "bigFile.txt");
    file.delete();/*from   ww  w . j a  v  a2s.  c om*/
    RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
    randomAccessFile.setLength(10 * 1024 * 1024);
    randomAccessFile.close();
    return file;
}

From source file:jp.andeb.obbutil.ObbUtilMain.java

private static boolean doRemove(String[] args) {
    if (args.length != 1) {
        printUsage(PROGNAME);/*from   w w w  . j av a  2 s .co m*/
        return false;
    }
    final File targetFile = new File(args[0]);
    final RandomAccessFile targetRaFile;
    try {
        targetRaFile = new RandomAccessFile(targetFile, "rw");
    } catch (FileNotFoundException e) {
        System.err.println("????: " + targetFile.getPath());
        return false;
    }
    try {
        final ObbInfoV1 obbInfo;
        try {
            obbInfo = ObbInfoV1.fromFile(targetRaFile);
        } catch (IOException e) {
            System.err
                    .println("????????: " + targetFile.getPath());
            return false;
        } catch (NotObbException e) {
            System.err.println(
                    "? OBB ???????: " + targetFile.getPath());
            return false;
        }

        final ByteBuffer obbInfoBytes = obbInfo.toBytes();
        targetRaFile.setLength(targetRaFile.length() - obbInfoBytes.remaining());
    } catch (IOException e) {
        System.err.println("OBB ??????: " + targetFile.getPath());
        return false;
    } finally {
        try {
            targetRaFile.close();
        } catch (IOException e) {
            System.err.println("OBB ??????: " + targetFile.getPath());
            return false;
        }
    }

    System.err.println("OBB ???????: " + targetFile.getPath());
    return true;
}

From source file:com.turn.ttorrent.client.TorrentByteStorage.java

/** Move the partial file to its final location.
 *
 * <p>/*from  w  w w .  j a  v  a 2 s .  c o m*/
 * This method needs to make sure reads can still happen seemlessly during
 * the operation. The partial is first flushed to the storage device before
 * being copied to its target location. The {@link FileChannel} is then
 * switched to this new file before the partial is removed.
 * </p>
 */
public synchronized void complete() throws IOException {
    this.channel.force(true);

    // Nothing more to do if we're already on the target file.
    if (this.current.equals(this.target)) {
        return;
    }

    FileUtils.deleteQuietly(this.target);
    FileUtils.copyFile(this.current, this.target);

    logger.debug("Re-opening torrent byte storage at " + this.target.getAbsolutePath() + ".");

    RandomAccessFile raf = new RandomAccessFile(this.target, "rw");
    raf.setLength(this.size);

    this.channel = raf.getChannel();
    this.raf.close();
    this.raf = raf;
    this.current = this.target;

    FileUtils.deleteQuietly(this.partial);
}

From source file:com.replaymod.replaystudio.launcher.ReverseLauncher.java

public void launch(CommandLine cmd) throws Exception {
    ZipFile file = new ZipFile(cmd.getArgs()[0]);
    ZipEntry entry = file.getEntry("recording.tmcpr");
    if (entry == null) {
        throw new IOException("Input file is not a valid replay file.");
    }/*from  w ww  .  java 2s .c o  m*/
    long size = entry.getSize();
    if (size == -1) {
        throw new IOException("Uncompressed size of recording.tmcpr not set.");
    }

    InputStream from = file.getInputStream(entry);
    RandomAccessFile to = new RandomAccessFile(cmd.getArgs()[1], "rw");

    to.setLength(size);
    int nRead;
    long pos = size;
    byte[] buffer = new byte[8192];

    long lastUpdate = -1;
    while (true) {
        long pct = 100 - pos * 100 / size;
        if (lastUpdate != pct) {
            System.out.print("Reversing " + size + " bytes... " + pct + "%\r");
            lastUpdate = pct;
        }
        int next = readInt(from);
        int length = readInt(from);
        if (next == -1 || length == -1) {
            break; // reached end of stream
        }
        // Increase buffer if necessary
        if (length + 8 > buffer.length) {
            buffer = new byte[length + 8];
        }
        buffer[0] = (byte) ((next >>> 24) & 0xFF);
        buffer[1] = (byte) ((next >>> 16) & 0xFF);
        buffer[2] = (byte) ((next >>> 8) & 0xFF);
        buffer[3] = (byte) (next & 0xFF);
        buffer[4] = (byte) ((length >>> 24) & 0xFF);
        buffer[5] = (byte) ((length >>> 16) & 0xFF);
        buffer[6] = (byte) ((length >>> 8) & 0xFF);
        buffer[7] = (byte) (length & 0xFF);

        nRead = 0;
        while (nRead < length) {
            nRead += from.read(buffer, 8 + nRead, length - nRead);
        }

        pos -= length + 8;
        to.seek(pos);
        to.write(buffer, 0, length + 8);
    }

    from.close();
    to.close();

    System.out.println("\nDone!");
}