Example usage for java.io RandomAccessFile writeBytes

List of usage examples for java.io RandomAccessFile writeBytes

Introduction

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

Prototype

@SuppressWarnings("deprecation")
public final void writeBytes(String s) throws IOException 

Source Link

Document

Writes the string to the file as a sequence of bytes.

Usage

From source file:com.qubole.rubix.core.TestCachingInputStream.java

private void writeZeros(String filename, int start, int end) throws IOException {
    File file = new File(filename);
    RandomAccessFile raf = new RandomAccessFile(file, "rw");
    raf.seek(start);//  w w  w  . j  a  va2s  . c o  m
    String s = "0";
    StandardCharsets.UTF_8.encode(s);
    for (int i = 0; i < (end - start); i++) {
        raf.writeBytes(s);
    }
    raf.close();
}

From source file:org.pieShare.pieShareApp.service.historyService.HistoryServiceNGTest.java

@Test
public void shouldSyncLocalDirWithHistory() throws Exception {

    File dirA = new File(testWorkingDir, "A");
    dirA.mkdirs();/*  w w w  .  j  a  v a2  s.co  m*/
    File dirB = new File(testWorkingDir, "B");
    dirB.mkdirs();

    RandomAccessFile fileA = new RandomAccessFile(new File(dirA, "file"), "rw");
    fileA.writeBytes("This is my test file A!!!");
    fileA.close();

    RandomAccessFile fileB = new RandomAccessFile(new File(dirB, "file"), "rw");
    fileB.writeBytes("This is my test file B!!!");
    fileB.close();

    PieFile pieFileA = this.fileService.getPieFile(new File(dirA, "file"));
    PieFile pieFileB = this.fileService.getPieFile(new File(dirB, "file"));
    PieFolder pieFolderA = this.folderService.getPieFolder(dirA);
    PieFolder pieFolderB = this.folderService.getPieFolder(dirB);

    this.historyService.setDateProvider(new Provider<Date>() {
        @Override
        public Date get() {
            return new Date();
        }
    });

    this.historyService.syncLocalFilders();

    //todo: for some reason the deleted flag is true after the persist
    List<PieFile> pieFiles = this.historyService.getPieFiles(pieFileA.getMd5());
    Assert.assertEquals(pieFiles.size(), 1);
    Assert.assertTrue(pieFiles.contains(pieFileA));

    pieFiles = this.historyService.getPieFiles();
    Assert.assertEquals(pieFiles.size(), 2);
    Assert.assertTrue(pieFiles.contains(pieFileA));
    Assert.assertTrue(pieFiles.contains(pieFileB));

    List<PieFolder> pieFolders = this.historyService.getPieFolders();
    Assert.assertEquals(pieFolders.size(), 2);
    Assert.assertTrue(pieFolders.contains(pieFolderA));
    Assert.assertTrue(pieFolders.contains(pieFolderB));

    FileUtils.deleteDirectory(new File(testWorkingDir, "A"));

    final Date dateDelete = new Date();
    this.historyService.setDateProvider(new Provider<Date>() {
        @Override
        public Date get() {
            return dateDelete;
        }
    });

    pieFileA.setDeleted(true);
    pieFileA.setLastModified(dateDelete.getTime());
    pieFolderA.setDeleted(true);
    pieFolderA.setLastModified(dateDelete.getTime());

    this.historyService.syncLocalFilders();

    pieFiles = this.historyService.getPieFiles(pieFileA.getMd5());
    Assert.assertEquals(pieFiles.size(), 1);
    Assert.assertTrue(pieFiles.contains(pieFileA));

    pieFiles = this.historyService.getPieFiles();
    Assert.assertEquals(pieFiles.size(), 2);
    Assert.assertTrue(pieFiles.contains(pieFileA));
    Assert.assertTrue(pieFiles.contains(pieFileB));

    pieFolders = this.historyService.getPieFolders();
    Assert.assertEquals(pieFolders.size(), 2);
    Assert.assertTrue(pieFolders.contains(pieFolderA));
    Assert.assertTrue(pieFolders.contains(pieFolderB));
}

From source file:jm.web.Archivo.java

public String getArchivoXml(String path, String tabla, String clave, String campoNombre, String campo) {
    this._archivoNombre = "";
    try {/*from   ww w. j ava 2 s . co m*/
        ResultSet res = this.consulta("select * from " + tabla + " where clave_acceso='" + 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 + ".xml",
                                "rw");
                        archivo.writeBytes(campo);
                        archivo.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            res.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return this._archivoNombre;
}

From source file:org.apache.activemq.store.kahadb.KahaDBStoreRecoveryBrokerTest.java

@Override
@SuppressWarnings("resource")
protected BrokerService createRestartedBroker() throws Exception {

    // corrupting index
    File index = new File(kahaDbDirectoryName + "/db.data");
    RandomAccessFile raf = new RandomAccessFile(index, "rw");
    switch (failTest) {
    case FailToLoad:
        index.delete();//w  ww .ja v a 2  s. com
        raf = new RandomAccessFile(index, "rw");
        raf.seek(index.length());
        raf.writeBytes("corrupt");
        break;
    case LoadInvalid:
        // page size 0
        raf.seek(0);
        raf.writeBytes("corrupt and cannot load metadata");
        break;
    case LoadCorrupt:
        // loadable but invalid metadata
        // location of order index low priority index for first destination...
        raf.seek(8 * 1024 + 57);
        raf.writeLong(Integer.MAX_VALUE - 10);
        break;
    case LoadOrderIndex0:
        // loadable but invalid metadata
        // location of order index default priority index size
        // so looks like there are no ids in the order index
        // picked up by setCheckForCorruptJournalFiles
        raf.seek(12 * 1024 + 21);
        raf.writeShort(0);
        raf.writeChar(0);
        raf.writeLong(-1);
        break;
    default:
    }
    raf.close();

    // starting broker
    BrokerService broker = new BrokerService();
    KahaDBStore kaha = new KahaDBStore();
    kaha.setCheckForCorruptJournalFiles(failTest == CorruptionType.LoadOrderIndex0);
    // uncomment if you want to test archiving
    //kaha.setArchiveCorruptedIndex(true);
    kaha.setDirectory(new File(kahaDbDirectoryName));
    broker.setPersistenceAdapter(kaha);
    return broker;
}

From source file:hydrograph.ui.perspective.dialog.PreStartActivity.java

private void updateData(byte[] text, String javaHome, String end, RandomAccessFile file) throws IOException {
    String data = new String(text);
    data = StringUtils.replace(data, end, javaHome);
    file.setLength(data.length());/*www  . ja v a  2 s. c  om*/
    file.writeBytes(data);
}

From source file:org.openengsb.connector.promreport.internal.ProcessFileStore.java

private void writeTo(File proFile, ProcessInstance pi) {
    LOGGER.debug("write process instance {} to {}", pi.getId(), proFile.getName());
    RandomAccessFile raf = null;
    try {//from  w  w w .  j  a va 2  s  .  c om
        raf = new RandomAccessFile(proFile, "rw");
        long position = findLastProcess(raf);
        raf.seek(position);
        String s = marshal(pi);
        raf.writeBytes(s);
        raf.write(0x0A);
        raf.writeBytes(ENDDOC);
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        try {
            raf.close();
        } catch (IOException e) {
        }
    }
}

From source file:org.apache.cassandra.db.VerifyTest.java

@Test
public void testVerifyCorruptRowCorrectDigest() throws IOException, WriteTimeoutException {
    CompactionManager.instance.disableAutoCompaction();
    Keyspace keyspace = Keyspace.open(KEYSPACE);
    ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(CORRUPT_CF2);

    fillCF(cfs, KEYSPACE, CORRUPT_CF2, 2);

    List<Row> rows = cfs.getRangeSlice(Util.range("", ""), null, new IdentityQueryFilter(), 1000);

    SSTableReader sstable = cfs.getSSTables().iterator().next();

    // overwrite one row with garbage
    long row0Start = sstable.getPosition(RowPosition.ForKey.get(ByteBufferUtil.bytes("0"), sstable.partitioner),
            SSTableReader.Operator.EQ).position;
    long row1Start = sstable.getPosition(RowPosition.ForKey.get(ByteBufferUtil.bytes("1"), sstable.partitioner),
            SSTableReader.Operator.EQ).position;
    long startPosition = row0Start < row1Start ? row0Start : row1Start;
    long endPosition = row0Start < row1Start ? row1Start : row0Start;

    RandomAccessFile file = new RandomAccessFile(sstable.getFilename(), "rw");
    file.seek(startPosition);//from   w w  w  .  j av  a  2s  . c  om
    file.writeBytes(StringUtils.repeat('z', (int) 2));
    file.close();

    // Update the Digest to have the right Checksum
    writeChecksum(simpleFullChecksum(sstable.getFilename()), sstable.descriptor.filenameFor(Component.DIGEST));

    Verifier verifier = new Verifier(cfs, sstable, false);

    // First a simple verify checking digest, which should succeed
    try {
        verifier.verify(false);
    } catch (CorruptSSTableException err) {
        fail("Simple verify should have succeeded as digest matched");
    }

    // Now try extended verify
    try {
        verifier.verify(true);

    } catch (CorruptSSTableException err) {
        return;
    }
    fail("Expected a CorruptSSTableException to be thrown");

}

From source file:edu.harvard.i2b2.adminTool.dataModel.PatientMappingFactory.java

public static void append(RandomAccessFile f, String outString) throws IOException {
    try {//from w  ww.j a  v  a2  s . c o m
        f.seek(f.length());
        f.writeBytes(outString);
    } catch (IOException e) {
        throw new IOException("trouble writing to random access file.");
    }
    return;
}

From source file:hydrograph.ui.perspective.dialog.PreStartActivity.java

private boolean updateINIFile(String javaHome) {
    logger.debug("Updating JAVA_HOME in ini file ::" + javaHome);
    javaHome = "-vm\n" + javaHome + "\n";
    RandomAccessFile file = null;
    boolean isUpdated = false;
    try {//from   ww  w. java2s .c om
        file = new RandomAccessFile(new File(HYDROGRAPH_INI), "rw");
        byte[] text = new byte[(int) file.length()];
        file.readFully(text);
        file.seek(0);
        file.writeBytes(javaHome);
        file.write(text);
        isUpdated = true;
    } catch (IOException ioException) {
        logger.error("IOException occurred while updating " + HYDROGRAPH_INI + " file", ioException);
    } finally {
        try {
            if (file != null) {
                file.close();
            }
        } catch (IOException ioException) {
            logger.error("IOException occurred while updating " + HYDROGRAPH_INI + " file", ioException);
        }
    }
    return isUpdated;
}

From source file:edu.harvard.i2b2.patientMapping.ui.PatientIDConversionJFrame.java

private void append(RandomAccessFile f, String outString) throws IOException {
    try {// ww w .  java  2s .c  o  m
        f.seek(f.length());
        f.writeBytes(outString);
    } catch (IOException e) {
        throw new IOException("trouble writing to random access file.");
    }
    return;
}