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:eu.trentorise.smartcampus.feedback.test.TestFeedbackManagers.java

private void writeTestFile(byte[] data) throws IOException {
    RandomAccessFile f = new RandomAccessFile("src/test/resources/android_copy.jpg", "rw");
    f.write(data);
    f.close();/* w w w  . j a  va  2 s  .c o  m*/
}

From source file:org.jcodec.movtool.Undo.java

private void undo(String fineName) throws IOException {
    List<Atom> versions = list(fineName);
    if (versions.size() < 2) {
        System.err.println("Nowhere to rollback.");
        return;//from w  w w. j a  va2 s .  c  o m
    }
    RandomAccessFile raf = null;
    try {
        raf = new RandomAccessFile(new File(fineName), "rw");
        raf.seek(versions.get(versions.size() - 2).getOffset() + 4);
        raf.write(new byte[] { 'm', 'o', 'o', 'v' });
        raf.seek(versions.get(versions.size() - 1).getOffset() + 4);
        raf.write(new byte[] { 'f', 'r', 'e', 'e' });
    } finally {
        raf.close();
    }
}

From source file:com.github.nlloyd.hornofmongo.MongoScope.java

public static Object fuzzFile(Context cx, Scriptable thisObj, Object[] args, Function funObj) {
    if (args.length != 2)
        Context.throwAsScriptRuntimeEx(new MongoScriptException("fuzzFile takes 2 arguments"));
    File fileToFuzz;//from  w  w  w . ja va2s .c  om
    try {
        fileToFuzz = resolveFilePath((MongoScope) thisObj, Context.toString(args[0])).getCanonicalFile();
    } catch (IOException e) {
        Context.throwAsScriptRuntimeEx(new MongoScriptException(e));
        return null;
    }
    RandomAccessFile fuzzFile = null;
    try {
        fuzzFile = new RandomAccessFile(fileToFuzz, "rw");
        long fuzzPosition = Double.valueOf(Context.toNumber(args[1])).longValue();
        fuzzFile.seek(fuzzPosition);
        int byteToFuzz = fuzzFile.readByte();
        byteToFuzz = ~byteToFuzz;
        fuzzFile.seek(fuzzPosition);
        fuzzFile.write(byteToFuzz);
        fuzzFile.close();
    } catch (FileNotFoundException e) {
        Context.throwAsScriptRuntimeEx(e);
    } catch (IOException e) {
        Context.throwAsScriptRuntimeEx(e);
    } finally {
        if (fuzzFile != null) {
            try {
                fuzzFile.close();
            } catch (IOException e) {
            }
        }
    }

    return Undefined.instance;
}

From source file:org.ofbiz.product.imagemanagement.ImageManagementServices.java

public static Map<String, Object> createContentThumbnail(DispatchContext dctx,
        Map<String, ? extends Object> context, GenericValue userLogin, ByteBuffer imageData, String productId,
        String imageName) {/*from   w w w . j  a  va 2 s .c  o  m*/
    Map<String, Object> result = FastMap.newInstance();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    Locale locale = (Locale) context.get("locale");
    //FIXME can be removed ?
    // String imageFilenameFormat = UtilProperties.getPropertyValue("catalog", "image.filename.format");
    String imageServerPath = FlexibleStringExpander
            .expandString(UtilProperties.getPropertyValue("catalog", "image.management.path"), context);
    String nameOfThumb = FlexibleStringExpander.expandString(
            UtilProperties.getPropertyValue("catalog", "image.management.nameofthumbnail"), context);

    // Create content for thumbnail
    Map<String, Object> contentThumb = FastMap.newInstance();
    contentThumb.put("contentTypeId", "DOCUMENT");
    contentThumb.put("userLogin", userLogin);
    Map<String, Object> contentThumbResult = FastMap.newInstance();
    try {
        contentThumbResult = dispatcher.runSync("createContent", contentThumb);
    } catch (GenericServiceException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }

    String contentIdThumb = (String) contentThumbResult.get("contentId");
    result.put("contentIdThumb", contentIdThumb);

    /*// File to use for image thumbnail
    FlexibleStringExpander filenameExpanderThumb = FlexibleStringExpander.getInstance(imageFilenameFormat);
    String fileLocationThumb = filenameExpanderThumb.expandString(UtilMisc.toMap("location", "products", "type", "small", "id", contentIdThumb));
    String filenameToUseThumb = fileLocationThumb;
    if (fileLocationThumb.lastIndexOf("/") != -1) {
    filenameToUseThumb = fileLocationThumb.substring(fileLocationThumb.lastIndexOf("/") + 1);
    }
            
    String fileContentType = (String) context.get("_uploadedFile_contentType");
    if (fileContentType.equals("image/pjpeg")) {
    fileContentType = "image/jpeg";
    } else if (fileContentType.equals("image/x-png")) {
    fileContentType = "image/png";
    }
            
    List<GenericValue> fileExtensionThumb = FastList.newInstance();
    try {
    fileExtensionThumb = delegator.findByAnd("FileExtension", UtilMisc.toMap("mimeTypeId", fileContentType));
    } catch (GenericEntityException e) {
    Debug.logError(e, module);
    return ServiceUtil.returnError(e.getMessage());
    }
            
    GenericValue extensionThumb = EntityUtil.getFirst(fileExtensionThumb);
    if (extensionThumb != null) {
    filenameToUseThumb += "." + extensionThumb.getString("fileExtensionId");
    }*/
    //String uploadFileName = (String) context.get("_uploadedFile_fileName");
    String filenameToUseThumb = imageName.substring(0, imageName.indexOf(".")) + nameOfThumb;
    String fileContentType = (String) context.get("_uploadedFile_contentType");
    if (fileContentType.equals("image/pjpeg")) {
        fileContentType = "image/jpeg";
    } else if (fileContentType.equals("image/x-png")) {
        fileContentType = "image/png";
    }

    List<GenericValue> fileExtensionThumb = FastList.newInstance();
    try {
        fileExtensionThumb = delegator.findByAnd("FileExtension",
                UtilMisc.toMap("mimeTypeId", fileContentType));
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }

    GenericValue extensionThumb = EntityUtil.getFirst(fileExtensionThumb);
    if (extensionThumb != null) {

        filenameToUseThumb += "." + extensionThumb.getString("fileExtensionId");
    }
    result.put("filenameToUseThumb", filenameToUseThumb);
    // Create image file thumbnail to folder product id.
    File fileOriginalThumb = new File(imageServerPath + "/" + productId + "/" + filenameToUseThumb);
    try {
        RandomAccessFile outFileThumb = new RandomAccessFile(fileOriginalThumb, "rw");
        outFileThumb.write(imageData.array());
        outFileThumb.close();
    } catch (FileNotFoundException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductImageViewUnableWriteFile",
                UtilMisc.toMap("fileName", fileOriginalThumb.getAbsolutePath()), locale));
    } catch (IOException e) {
        Debug.logError(e, module);
        return ServiceUtil
                .returnError(UtilProperties.getMessage(resource, "ProductImageViewUnableWriteBinaryData",
                        UtilMisc.toMap("fileName", fileOriginalThumb.getAbsolutePath()), locale));
    }

    Map<String, Object> resultResizeThumb = FastMap.newInstance();
    try {
        resultResizeThumb.putAll(ImageManagementServices.scaleImageMangementInAllSize(context,
                filenameToUseThumb, "thumbnail", productId));
    } catch (IOException e) {
        String errMsg = "Scale additional image in all different sizes is impossible : " + e.toString();
        Debug.logError(e, errMsg, module);
        return ServiceUtil.returnError(errMsg);
    } catch (JDOMException e) {
        String errMsg = "Errors occur in parsing ImageProperties.xml : " + e.toString();
        Debug.logError(e, errMsg, module);
        return ServiceUtil.returnError(errMsg);
    }
    return result;
}

From source file:jazsync.UploadTests.java

/**
 * Sets the fields of an Upload object and tests whether the {@link Upload#getInputStream()}
 * returns the upload data in the expected format.
 * //from ww  w .  j  a  v  a 2s  .c o  m
 * @throws IOException
 */
@Test
public void testGetInputStream() throws IOException {

    Upload um = new Upload();

    um.setVersion("testVersion");
    um.setBlocksize(1024);
    um.setFilelength(32768);
    um.setSha1("sha1checksum");

    File testFile = File.createTempFile("Upload", "Test");
    RandomAccessFile randAccess = new RandomAccessFile(testFile, "rw");
    String inString = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXABCDEYZXXXXX";
    randAccess.write(inString.getBytes("US-ASCII"));

    ByteRangeWriter dataRanges = new ByteRangeWriter(16384);
    dataRanges.add(new Range(45, 50), randAccess);
    dataRanges.add(new Range(51, 52), randAccess);
    um.setDataStream(dataRanges.getInputStream());

    RelocWriter relocRanges = new RelocWriter(16384);
    relocRanges.add(new RelocateRange(new Range(2, 6), 123));
    relocRanges.add(new RelocateRange(new Range(8, 98), 987));
    um.setRelocStream(relocRanges.getInputStream());

    InputStream uploadIn = um.getInputStream();
    String actString = IOUtils.toString(uploadIn, Upload.CHARSET);
    String expString = version + filelength + blocksize + sha1 + relocString + rangeString;

    uploadIn.close();
    randAccess.close();

    System.out.println(actString);
    Assert.assertEquals(expString, actString);

}

From source file:com.example.android.vault.EncryptedDocumentTest.java

public void testBitTwiddle() throws Exception {
    final EncryptedDocument doc = new EncryptedDocument(4, mFile, mDataKey, mMacKey);

    // write some metadata
    final JSONObject before = new JSONObject();
    before.put("twiddle", "twiddle");
    doc.writeMetadataAndContent(before, null);

    final RandomAccessFile f = new RandomAccessFile(mFile, "rw");
    f.seek(f.length() - 4);/*from  w w  w  . j  av a2 s  . c om*/
    f.write(0x00);
    f.close();

    try {
        doc.readMetadata();
        fail("somehow passed hmac");
    } catch (DigestException expected) {
    }
}

From source file:savant.util.CachedSeekableStream.java

private void initCache() throws IOException {

    cacheFile = RemoteFileCache.getCacheFile(uri.toURL(), getSource(), bufferSize, length());

    // Calculate number of blocks in file
    numBlocks = (int) Math.ceil(length() / (double) bufferSize);

    // Create the cacheFile with an empty index section.
    RandomAccessFile raf = new RandomAccessFile(cacheFile, "rw");
    for (int i = 0; i < numBlocks; i++) {
        //write 0x0000
        raf.write(0);
        raf.write(0);//from   www.  j  a v a2s.  com
        raf.write(0);
        raf.write(0);
    }
    raf.close();
}

From source file:jm.web.Archivo.java

public String getArchivo(String path, int clave) {
    this._archivoNombre = "";
    try {//w  ww  . ja v a2  s  .  co  m
        ResultSet res = this.consulta("select * from tbl_archivo where id_archivo=" + clave + ";");
        if (res.next()) {
            this._archivoNombre = (res.getString("nombre") != null) ? res.getString("nombre") : "";
            try {
                this._archivo = new File(path, this._archivoNombre);
                if (!this._archivo.exists()) {
                    byte[] bytes = (res.getString("archivo") != null) ? res.getBytes("archivo") : null;
                    RandomAccessFile archivo = new RandomAccessFile(path + this._archivoNombre, "rw");
                    archivo.write(bytes);
                    archivo.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            res.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return this._archivoNombre;
}

From source file:uk.bl.wa.util.CachedSeekableStream.java

private void initCache() throws IOException {

    cacheFile = File.createTempFile("temp", ".tmp");

    // Calculate number of blocks in file
    numBlocks = (int) Math.ceil(length() / (double) bufferSize);

    // Create the cacheFile with an empty index section.
    RandomAccessFile raf = new RandomAccessFile(cacheFile, "rw");
    for (int i = 0; i < numBlocks; i++) {
        //write 0x0000
        raf.write(0);
        raf.write(0);//from w ww.j a va  2  s .  c o  m
        raf.write(0);
        raf.write(0);
    }
    raf.close();
}

From source file:jm.web.Archivo.java

public String getArchivo(String path, String tabla, String clave, String campoNombre, String campoBytea) {
    this._archivoNombre = "";
    try {/*from   w  w  w.  j  a  va 2 s .c o  m*/
        ResultSet res = this.consulta(
                "select * from " + tabla + " where " + tabla.replace("tbl_", "id_") + "=" + clave + ";");
        if (res.next()) {
            this._archivoNombre = res.getString(campoNombre) != null ? res.getString(campoNombre) : "";
            if (this._archivoNombre.compareTo("") != 0) {
                try {
                    this._archivo = new File(path, this._archivoNombre);
                    if (!this._archivo.exists()) {
                        byte[] bytes = (res.getString(campoBytea) != null) ? res.getBytes(campoBytea) : null;
                        RandomAccessFile archivo = new RandomAccessFile(path + this._archivoNombre, "rw");
                        archivo.write(bytes);
                        archivo.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            res.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return this._archivoNombre;
}