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:Main.java

public static void main(String[] args) {
    try {/*www  .  j ava 2s .c  o m*/
        RandomAccessFile raf = new RandomAccessFile("c:/test.txt", "rw");

        raf.writeBytes("Hello World from java2s.com");

        raf.seek(0);

        System.out.println(raf.readLine());

        raf.seek(0);

        raf.writeBytes("This is an example from java2s.com");

        raf.seek(0);

        System.out.println(raf.readLine());
        raf.close();
    } catch (IOException ex) {
        ex.printStackTrace();
    }

}

From source file:Main.java

License:asdf

public static void main(String[] args) throws Exception {
    RandomAccessFile randomAccessFile = null;

    String line1 = "line\n";
    String line2 = "asdf1234\n";

    // read / write permissions
    randomAccessFile = new RandomAccessFile("yourFile.dat", "rw");

    randomAccessFile.writeBytes(line1);
    randomAccessFile.writeBytes(line2);//ww w  .  j  a  v a 2s .co  m

    // Place the file pointer at the end of the first line
    randomAccessFile.seek(line1.length());

    byte[] buffer = new byte[line2.length()];
    randomAccessFile.read(buffer);
    System.out.println(new String(buffer));

    randomAccessFile.close();
}

From source file:Main.java

License:asdf

public static void main(String[] args) throws Exception {
    RandomAccessFile randomAccessFile = null;

    String line1 = "java2s.com\n";
    String line2 = "asdf1234\n";

    // read / write permissions
    randomAccessFile = new RandomAccessFile("yourFile.dat", "rw");

    randomAccessFile.writeBytes(line1);
    randomAccessFile.writeBytes(line2);/*  www . j a  v  a  2 s  . co m*/

    // Place the file pointer at the end of the first line
    randomAccessFile.seek(line1.length());

    byte[] buffer = new byte[line2.length()];
    randomAccessFile.read(buffer);
    System.out.println(new String(buffer));

    randomAccessFile.close();
}

From source file:edu.usc.qufd.Main.java

/**
 * The main method.// w  ww  .j  av  a2  s .c o m
 *
 * @param args the arguments
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static void main(String[] args) throws IOException {
    if (parseInputs(args) == false) {
        System.exit(-1); //The input files do not exist
    }

    /*
     * Parsing inputs: fabric & qasm file
     */
    PrintWriter outputFile;
    RandomAccessFile raf = null;
    String latencyPlaceHolder;
    if (RuntimeConfig.OUTPUT_TO_FILE) {
        latencyPlaceHolder = "Total Latency: " + Long.MAX_VALUE + " us" + System.lineSeparator();
        raf = new RandomAccessFile(outputFileAddr, "rws");
        //removing the old values in the file
        raf.setLength(0);
        //writing a place holder for the total latency
        raf.writeBytes(latencyPlaceHolder);
        raf.close();

        outputFile = new PrintWriter(new BufferedWriter(new FileWriter(outputFileAddr, true)), true);
    } else { //writing to stdout
        outputFile = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), true);
    }
    /* parsing the input*/
    layout = LayoutParser.parse(pmdFileAddr);
    qasm = QASMParser.QASMParser(qasmFileAddr, layout);

    long totalLatency = qufd(outputFile);

    if (RuntimeConfig.OUTPUT_TO_FILE) {
        outputFile.close();
        //Over writing the place holder with the actual latency
        String latencyActual = "Total Latency: " + totalLatency + " " + layout.getTimeUnit();
        latencyActual = StringUtils.rightPad(latencyActual,
                latencyPlaceHolder.length() - System.lineSeparator().length());
        raf = new RandomAccessFile(outputFileAddr, "rws");
        //Writing to the top of a file
        raf.seek(0);
        //writing the actual total latency in the at the top of the output file
        raf.writeBytes(latencyActual + System.lineSeparator());
        raf.close();
    } else {
        outputFile.flush();
        System.out.println("Total Latency: " + totalLatency + " " + layout.getTimeUnit());
    }

    if (RuntimeConfig.VERBOSE) {
        System.out.println("Done.");
    }
    outputFile.close();
}

From source file:Main.java

public static void append(String fileName, String text) throws Exception {
    File f = new File(fileName);
    long fileLength = f.length();
    RandomAccessFile raf = new RandomAccessFile(f, "rw");
    raf.seek(fileLength);//from ww  w.  j  a  v  a  2  s.c  o  m
    raf.writeBytes(text);
    raf.close();
}

From source file:com.github.neoio.nio.util.NIOUtils.java

public static FileLock tryLock(File file) {
    FileLock toReturn = null;//from ww  w.j a va  2 s. c  o  m

    try {
        RandomAccessFile raf = new RandomAccessFile(file, "rw");

        try {
            FileChannel channel = raf.getChannel();
            toReturn = channel.tryLock();
            raf.writeBytes("lock file for: " + ManagementFactory.getRuntimeMXBean().getName());
        } finally {
            if (toReturn == null)
                raf.close();
        }
    } catch (OverlappingFileLockException e) {
        toReturn = null;
    } catch (FileNotFoundException e) {
        toReturn = null;
    } catch (IOException e) {
        toReturn = null;
    }

    return toReturn;
}

From source file:org.apache.jackrabbit.oak.run.SegmentUtils.java

static void compact(File directory, boolean force) throws IOException {
    FileStore store = openFileStore(directory.getAbsolutePath(), force);
    try {//from   w w  w .  j ava 2  s.  c  o m
        boolean persistCM = Boolean.getBoolean("tar.PersistCompactionMap");
        CompactionStrategy compactionStrategy = new CompactionStrategy(false,
                CompactionStrategy.CLONE_BINARIES_DEFAULT, CompactionStrategy.CleanupType.CLEAN_ALL, 0,
                CompactionStrategy.MEMORY_THRESHOLD_DEFAULT) {

            @Override
            public boolean compacted(Callable<Boolean> setHead) throws Exception {
                // oak-run is doing compaction single-threaded
                // hence no guarding needed - go straight ahead
                // and call setHead
                return setHead.call();
            }
        };
        compactionStrategy.setOfflineCompaction(true);
        compactionStrategy.setPersistCompactionMap(persistCM);
        store.setCompactionStrategy(compactionStrategy);
        store.compact();
    } finally {
        store.close();
    }

    System.out.println("    -> cleaning up");
    store = openFileStore(directory.getAbsolutePath(), false);
    try {
        for (File file : store.cleanup()) {
            if (!file.exists() || file.delete()) {
                System.out.println("    -> removed old file " + file.getName());
            } else {
                System.out.println("    -> failed to remove old file " + file.getName());
            }
        }

        String head;
        File journal = new File(directory, "journal.log");
        JournalReader journalReader = new JournalReader(journal);
        try {
            head = journalReader.iterator().next() + " root " + System.currentTimeMillis() + "\n";
        } finally {
            journalReader.close();
        }

        RandomAccessFile journalFile = new RandomAccessFile(journal, "rw");
        try {
            System.out.println("    -> writing new " + journal.getName() + ": " + head);
            journalFile.setLength(0);
            journalFile.writeBytes(head);
            journalFile.getChannel().force(false);
        } finally {
            journalFile.close();
        }
    } finally {
        store.close();
    }
}

From source file:org.apache.jackrabbit.oak.run.SegmentTarUtils.java

static void compact(File directory, boolean force) throws IOException {
    FileStore store = newFileStoreBuilder(directory.getAbsolutePath(), force)
            .withGCOptions(defaultGCOptions().setOffline()).build();
    try {// w  w  w  .  j a  va2 s .  c  om
        store.compact();
    } finally {
        store.close();
    }

    System.out.println("    -> cleaning up");
    store = newFileStoreBuilder(directory.getAbsolutePath(), force)
            .withGCOptions(defaultGCOptions().setOffline()).build();
    try {
        for (File file : store.cleanup()) {
            if (!file.exists() || file.delete()) {
                System.out.println("    -> removed old file " + file.getName());
            } else {
                System.out.println("    -> failed to remove old file " + file.getName());
            }
        }

        String head;
        File journal = new File(directory, "journal.log");
        JournalReader journalReader = new JournalReader(journal);
        try {
            head = journalReader.next() + " root " + System.currentTimeMillis() + "\n";
        } finally {
            journalReader.close();
        }

        RandomAccessFile journalFile = new RandomAccessFile(journal, "rw");
        try {
            System.out.println("    -> writing new " + journal.getName() + ": " + head);
            journalFile.setLength(0);
            journalFile.writeBytes(head);
            journalFile.getChannel().force(false);
        } finally {
            journalFile.close();
        }
    } finally {
        store.close();
    }
}

From source file:hoot.services.info.ErrorLog.java

public String generateExportLog() throws Exception {
    String fileId = UUID.randomUUID().toString();
    String outputPath = _tempOutputPath + "/" + fileId;

    String data = "";

    AboutResource about = new AboutResource();
    VersionInfo vInfo = about.getCoreVersionInfo();
    data = "\n************ CORE VERSION INFO ***********\n";
    data += vInfo.toString();/*from w w  w .  jav  a2s .com*/
    CoreDetail cd = about.getCoreVersionDetail();
    data += "\n************ CORE ENVIRONMENT ***********\n";
    if (cd != null) {
        data += StringUtils.join(cd.getEnvironmentInfo(), '\n');
    }

    data = "\n************ SERVICE VERSION INFO ***********\n";
    data += about.getServicesVersionInfo().toString();
    ServicesDetail sd = about.getServicesVersionDetail();
    if (sd != null) {
        data += "\n************ SERVICE DETAIL PROPERTY ***********\n";
        for (ServicesDetail.Property prop : sd.getProperties()) {
            String str = prop.getName() + " : " + prop.getValue() + "\n";
            data += str;
        }

        data += "\n************ SERVICE DETAIL RESOURCE ***********\n";
        for (ServicesDetail.ServicesResource res : sd.getResources()) {
            String str = res.getType() + " : " + res.getUrl() + "\n";
            data += str;
        }
    }

    data += "\n************ CATALINA LOG ***********\n";

    // 5MB Max
    int maxSize = 5000000;

    String logStr = getErrorlog(maxSize);

    RandomAccessFile raf = new RandomAccessFile(outputPath, "rw");
    raf.writeBytes(data + "\n" + logStr);
    raf.close();
    return outputPath;
}

From source file:com.phonegap.FileUtils.java

/**
 * Write contents of file.//from  w  w  w .j  a v a2  s. c om
 * 
 * @param filename         The name of the file.
 * @param data            The contents of the file.
 * @param offset         The position to begin writing the file.         
 * @throws FileNotFoundException, IOException
 */
public long write(String filename, String data, long offset) throws FileNotFoundException, IOException {
    RandomAccessFile file = new RandomAccessFile(filename, "rw");
    file.seek(offset);
    file.writeBytes(data);
    file.close();

    return data.length();
}