Example usage for java.io RandomAccessFile write

List of usage examples for java.io RandomAccessFile write

Introduction

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

Prototype

public void write(byte b[]) throws IOException 

Source Link

Document

Writes b.length bytes from the specified byte array to this file, starting at the current file pointer.

Usage

From source file:org.movsim.MovsimCoreMainWithExperiments.java

private static void appendFiles(File src, File dst, boolean writeFirstLine) throws IOException {

    LineIterator lIter = FileUtils.lineIterator(src);
    RandomAccessFile rFile = new RandomAccessFile(dst, "rw");

    rFile.seek(dst.length());/*  www . j  a va 2 s. co m*/

    long lineCount = 1;
    while (lIter.hasNext()) {
        String line = lIter.next();

        if (lineCount > 1 || writeFirstLine) {
            rFile.write((line + "\n").getBytes());
        }
        lineCount++;
    }
    lIter.close();
    rFile.close();
}

From source file:com.lightbox.android.bitmap.BitmapUtils.java

public static void writeBitmapInFile(File file, Bitmap bitmap, CompressFormat compressFormat,
        StringBuilder outMD5) throws IOException {
    // Ensure that the directory exist
    file.getParentFile().mkdirs();//from  w w  w  . jav a 2 s. c  o m

    OutputStream outputStream = null;
    try {
        if (outMD5 != null) {
            // We want a MD5: writing JPEG into a byte array
            outputStream = new ByteArrayOutputStream();
        } else {
            // Directly write to file
            try {
                outputStream = new BufferedOutputStream(new RandomAccessFileOutputStream(file), 65536);
            } catch (OutOfMemoryError e) {
                outputStream = new BufferedOutputStream(new RandomAccessFileOutputStream(file));
            }
        }
        boolean success = bitmap.compress(compressFormat, FULL_QUALITY, outputStream);
        if (!success) {
            throw new IOException(String.format("Unable to save bitmap as a %s file: %s",
                    (compressFormat == CompressFormat.JPEG) ? "jpeg" : "png",
                    file.getAbsoluteFile().toString()));
        } else {
            if (outMD5 != null) {
                // Calculate MD5 and write the file to disk
                long time = System.currentTimeMillis();
                byte[] jpeg = ((ByteArrayOutputStream) outputStream).toByteArray();
                if (outMD5 != null) {
                    outMD5.append(getMD5String(jpeg));
                }
                DebugLog.d(TAG, "Time to calculate MD5: " + (System.currentTimeMillis() - time));

                time = System.currentTimeMillis();
                RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rwd");
                randomAccessFile.write(jpeg);
                randomAccessFile.close();
                DebugLog.d(TAG, "Time to write to file: " + (System.currentTimeMillis() - time));
            }
        }
    } finally {
        IOUtils.closeQuietly(outputStream);
    }
}

From source file:com.feilong.tools.net.ZClientTest.java

/**
 * Gets the files./*from   w  w  w .j  a  v  a  2 s  .  c o m*/
 * 
 * @param ftp
 *            the ftp
 * @param localDir
 *            the local dir
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
private static void testGetFiles(FTPClient ftp, File localDir) throws IOException {
    String[] names = ftp.listNames();
    for (String name : names) {
        File file = new File(localDir.getPath() + File.separator + name);
        if (!file.exists()) {
            file.createNewFile();
        }
        long pos = file.length();
        RandomAccessFile raf = new RandomAccessFile(file, "rw");
        raf.seek(pos);
        ftp.setRestartOffset(pos);
        InputStream is = ftp.retrieveFileStream(name);
        if (is == null) {
            log.info("no such file:" + name);
        } else {
            log.info("start getting file:" + name);
            int b;
            while ((b = is.read()) != -1) {
                raf.write(b);
            }
            is.close();
            if (ftp.completePendingCommand()) {
                log.info("done!");
            } else {
                log.info("can't get file:" + name);
            }
        }
        raf.close();
    }
}

From source file:org.syncany.tests.unit.util.TestFileUtil.java

public static void changeRandomPartOfBinaryFile(File file) throws IOException {
    if (file != null && !file.exists()) {
        throw new IOException("File does not exist: " + file);
    }//  w  w  w.j  a va 2s.c  o  m

    if (file.isDirectory()) {
        throw new IOException("Cannot change directory: " + file);
    }

    // Prepare: random bytes at random position
    Random randomEngine = new Random();

    int fileSize = (int) file.length();
    int maxChangeBytesLen = 20;
    int maxChangeBytesStartPos = (fileSize - maxChangeBytesLen - 1 >= 0) ? fileSize - maxChangeBytesLen - 1 : 0;

    int changeBytesStartPos = (maxChangeBytesStartPos > 0) ? randomEngine.nextInt(maxChangeBytesStartPos) : 0;
    int changeBytesLen = (fileSize - changeBytesStartPos < maxChangeBytesLen)
            ? fileSize - changeBytesStartPos - 1
            : maxChangeBytesLen;

    byte[] changeBytes = new byte[changeBytesLen];
    randomEngine.nextBytes(changeBytes);

    // Write to file
    RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");

    randomAccessFile.seek(changeBytesStartPos);
    randomAccessFile.write(changeBytes);

    randomAccessFile.close();
}

From source file:Testing.TestMain.java

/**
 * https://github.com/mpatric/mp3agic-examples/blob/master/src/main/java/com/mpatric/mp3agic/example/Example.java
 *
 * @param mP3FileParm//from   ww  w  .java2  s  . c  o m
 * @throws UnsupportedTagException
 * @throws InvalidDataException
 * @throws IOException
 * @throws NotSupportedException
 */
public static void readFromMP3File(File mP3FileParm)
        throws UnsupportedTagException, InvalidDataException, IOException, NotSupportedException {

    Mp3File mp3file = new Mp3File(mP3FileParm);

    System.out.println("Length of this mp3 is: " + mp3file.getLengthInSeconds() + " seconds");
    System.out.println("Bitrate: " + mp3file.getBitrate() + " kbps " + (mp3file.isVbr() ? "(VBR)" : "(CBR)"));
    System.out.println("Sample rate: " + mp3file.getSampleRate() + " Hz");
    System.out.println("Has ID3v1 tag?: " + (mp3file.hasId3v1Tag() ? "YES" : "NO"));
    System.out.println("Has ID3v2 tag?: " + (mp3file.hasId3v2Tag() ? "YES" : "NO"));
    System.out.println("Has custom tag?: " + (mp3file.hasCustomTag() ? "YES" : "NO"));

    if (mp3file.hasId3v1Tag()) {
        ID3v1 id3v1Tag = mp3file.getId3v1Tag();
        System.out.println("Track: " + id3v1Tag.getTrack());
        System.out.println("Artist: " + id3v1Tag.getArtist());
        System.out.println("Title: " + id3v1Tag.getTitle());
        System.out.println("Album: " + id3v1Tag.getAlbum());
        System.out.println("Year: " + id3v1Tag.getYear());
        System.out.println("Genre: " + id3v1Tag.getGenre() + " (" + id3v1Tag.getGenreDescription() + ")");
        System.out.println("Comment: " + id3v1Tag.getComment());
    }

    ID3v1 id3v1Tag;
    if (mp3file.hasId3v1Tag()) {
        id3v1Tag = mp3file.getId3v1Tag();
    } else {
        id3v1Tag = new ID3v1Tag();
        mp3file.setId3v1Tag(id3v1Tag);
    }
    id3v1Tag.setTrack("5");
    id3v1Tag.setArtist("An Artist");
    id3v1Tag.setTitle("The Title");
    id3v1Tag.setAlbum("The Album");
    id3v1Tag.setYear("2001");
    id3v1Tag.setGenre(12);
    id3v1Tag.setComment("Some comment");
    mp3file.save("MyMp3File.mp3");

    if (mp3file.hasId3v2Tag()) {
        ID3v2 id3v2Tag = mp3file.getId3v2Tag();
        System.out.println("Track: " + id3v2Tag.getTrack());
        System.out.println("Artist: " + id3v2Tag.getArtist());
        System.out.println("Title: " + id3v2Tag.getTitle());
        System.out.println("Album: " + id3v2Tag.getAlbum());
        System.out.println("Year: " + id3v2Tag.getYear());
        System.out.println("Genre: " + id3v2Tag.getGenre() + " (" + id3v2Tag.getGenreDescription() + ")");
        System.out.println("Comment: " + id3v2Tag.getComment());
        System.out.println("Composer: " + id3v2Tag.getComposer());
        System.out.println("Publisher: " + id3v2Tag.getPublisher());
        System.out.println("Original artist: " + id3v2Tag.getOriginalArtist());
        System.out.println("Album artist: " + id3v2Tag.getAlbumArtist());
        System.out.println("Copyright: " + id3v2Tag.getCopyright());
        System.out.println("URL: " + id3v2Tag.getUrl());
        System.out.println("Encoder: " + id3v2Tag.getEncoder());
    }

    if (mp3file.hasId3v2Tag()) {
        ID3v2 id3v2Tag = mp3file.getId3v2Tag();
        byte[] imageData = id3v2Tag.getAlbumImage();
        if (imageData != null) {
            String mimeType = id3v2Tag.getAlbumImageMimeType();
            System.out.println("Mime type: " + mimeType);
            // Write image to file - can determine appropriate file extension from the mime type
            RandomAccessFile file = new RandomAccessFile("album-artwork", "rw");
            file.write(imageData);
            file.close();
        }
    }

    ID3v2 id3v2Tag;
    if (mp3file.hasId3v2Tag()) {
        id3v2Tag = mp3file.getId3v2Tag();
    } else {
        id3v2Tag = new ID3v24Tag();
        mp3file.setId3v2Tag(id3v2Tag);
    }
    id3v2Tag.setTrack("5");
    id3v2Tag.setArtist("An Artist");
    id3v2Tag.setTitle("The Title");
    id3v2Tag.setAlbum("The Album");
    id3v2Tag.setYear("2001");
    id3v2Tag.setGenre(12);
    id3v2Tag.setComment("Some comment");
    id3v2Tag.setComposer("The Composer");
    id3v2Tag.setPublisher("A Publisher");
    id3v2Tag.setOriginalArtist("Another Artist");
    id3v2Tag.setAlbumArtist("An Artist");
    id3v2Tag.setCopyright("Copyright");
    id3v2Tag.setUrl("http://foobar");
    id3v2Tag.setEncoder("The Encoder");
    mp3file.save("MyMp3File.mp3");
}

From source file:org.apache.hadoop.hdfs.TestClientReportBadBlock.java

/**
 * Corrupt a block on a data node. Replace the block file content with
 * content// ww w .  jav a  2  s.  c om
 * of 1, 2, ...BLOCK_SIZE.
 *
 * @param block
 *     the ExtendedBlock to be corrupted
 * @param dn
 *     the data node where the block needs to be corrupted
 * @throws FileNotFoundException
 * @throws IOException
 */
private static void corruptBlock(final ExtendedBlock block, final DataNode dn)
        throws FileNotFoundException, IOException {
    final File f = DataNodeTestUtils.getBlockFile(dn, block.getBlockPoolId(), block.getLocalBlock());
    final RandomAccessFile raFile = new RandomAccessFile(f, "rw");
    final byte[] bytes = new byte[(int) BLOCK_SIZE];
    for (int i = 0; i < BLOCK_SIZE; i++) {
        bytes[i] = (byte) (i);
    }
    raFile.write(bytes);
    raFile.close();
}

From source file:org.apache.hadoop.dfs.TestDatanodeBlockScanner.java

public static boolean corruptReplica(String blockName, int replica) throws IOException {
    Random random = new Random();
    File baseDir = new File(System.getProperty("test.build.data"), "dfs/data");
    boolean corrupted = false;
    for (int i = replica * 2; i < replica * 2 + 2; i++) {
        File blockFile = new File(baseDir, "data" + (i + 1) + "/current/" + blockName);
        if (blockFile.exists()) {
            // Corrupt replica by writing random bytes into replica
            RandomAccessFile raFile = new RandomAccessFile(blockFile, "rw");
            FileChannel channel = raFile.getChannel();
            String badString = "BADBAD";
            int rand = random.nextInt((int) channel.size() / 2);
            raFile.seek(rand);//from ww w  . j a v a 2 s  .co m
            raFile.write(badString.getBytes());
            raFile.close();
            corrupted = true;
        }
    }
    return corrupted;
}

From source file:org.odk.collect.android.tasks.SaveToDiskTask.java

/**
 * This method actually writes the xml to disk.
 * @param payload//from www  .  j a  va2 s .  co  m
 * @param path
 * @return
 */
static void exportXmlFile(ByteArrayPayload payload, String path) throws IOException {
    File file = new File(path);
    if (file.exists() && !file.delete()) {
        throw new IOException("Cannot overwrite " + path + ". Perhaps the file is locked?");
    }

    // create data stream
    InputStream is = payload.getPayloadStream();
    int len = (int) payload.getLength();

    // read from data stream
    byte[] data = new byte[len];
    //        try {
    int read = is.read(data, 0, len);
    if (read > 0) {
        // write xml file
        RandomAccessFile randomAccessFile = null;
        try {
            // String filename = path + File.separator +
            // path.substring(path.lastIndexOf(File.separator) + 1) + ".xml";
            randomAccessFile = new RandomAccessFile(file, "rws");
            randomAccessFile.write(data);
        } finally {
            if (randomAccessFile != null) {
                try {
                    randomAccessFile.close();
                } catch (IOException e) {
                    Log.e(t, "Error closing RandomAccessFile: " + path, e);
                }
            }
        }
    }
    //        } catch (IOException e) {
    //            Log.e(t, "Error reading from payload data stream");
    //            e.printStackTrace();
    //            return false;
    //        }
    //
    //        return false;
}

From source file:org.ofbiz.common.CommonServices.java

public static Map<String, Object> byteBufferTest(DispatchContext dctx, Map<String, ?> context) {
    ByteBuffer buffer1 = (ByteBuffer) context.get("byteBuffer1");
    ByteBuffer buffer2 = (ByteBuffer) context.get("byteBuffer2");
    String fileName1 = (String) context.get("saveAsFileName1");
    String fileName2 = (String) context.get("saveAsFileName2");
    String ofbizHome = System.getProperty("ofbiz.home");
    String outputPath1 = ofbizHome + (fileName1.startsWith("/") ? fileName1 : "/" + fileName1);
    String outputPath2 = ofbizHome + (fileName2.startsWith("/") ? fileName2 : "/" + fileName2);

    try {/*from www .j a  v  a2  s  .co m*/
        RandomAccessFile file1 = new RandomAccessFile(outputPath1, "rw");
        RandomAccessFile file2 = new RandomAccessFile(outputPath2, "rw");
        file1.write(buffer1.array());
        file2.write(buffer2.array());
    } catch (FileNotFoundException e) {
        Debug.logError(e, module);
    } catch (IOException e) {
        Debug.logError(e, module);
    }

    return ServiceUtil.returnSuccess();
}

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  . j ava 2 s .  c  om*/
            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();

}