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.andrewberman.sync.InheritMe.java

void downloadURLToFile(String url, File destFile) throws Exception {
    String origUrl = url;//from   w ww  .  j  a  v a 2  s. c  o  m
    File origFile = destFile;

    Thread.sleep(200);
    try {
        destFile.getParentFile().mkdirs();
        destFile.createNewFile();
    } catch (Exception e) {
        errS.println("Error creating new file: " + destFile + " . Skipping this PDF...");
        throw e;
    }
    out.print("   Downloading: ");

    url = StringEscapeUtils.escapeHtml(url);
    System.out.println(url);
    url = url.replaceAll(" ", "%20");
    GetMethod get = new GetMethod(url);
    ByteArrayOutputStream outS = new ByteArrayOutputStream();
    try {
        System.out.println("     Executing get...");
        httpclient.executeMethod(get);
        System.out.println("     Done!");

        BufferedInputStream in = new BufferedInputStream(get.getResponseBodyAsStream());
        int i = 0;
        int ind = 0;
        long length = get.getResponseContentLength();
        int starRatio = (int) length / 20;
        int numStars = 0;
        while ((i = in.read()) != -1) {
            if (length != -1 && ind % starRatio == 0) {
                status(" Downloading..." + repeat(".", ++numStars));
                out.print("*");
            }
            if (ind % 512 == 0) {
                waitOrExit();
            }
            outS.write(i);
            ind++;
        }

        in.close();
        outS.flush();

        RandomAccessFile raf = new RandomAccessFile(destFile, "rw");
        raf.write(outS.toByteArray());
        //         raf.write(get.getResponseBody());
        raf.close();
    } catch (java.net.SocketTimeoutException ste) {
        ste.printStackTrace();
        if (this.retriesLeft > 0) {
            this.retriesLeft--;
            System.out.println("Retries left: " + this.retriesLeft);
            this.downloadURLToFile(origUrl, origFile);
        } else {
            throw ste;
        }
    } finally {
        outS.close();
        get.releaseConnection();
        outS = null;
        out.print("\n");
    }
}

From source file:org.interreg.docexplore.authoring.AuthoringMenu.java

void writeRecent() {
    try {//  w ww .j  a  va  2 s. co m
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(recent);
        oos.flush();
        RandomAccessFile file = new RandomAccessFile(new File(DocExploreTool.getHomeDir(), "ATRecent"), "rw");
        file.setLength(0);
        file.write(baos.toByteArray());
        file.close();
        oos.close();

        //         ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(new File("ATRecent"), false));
        //         out.writeObject(recent);
        //         out.close();
    } catch (Exception e) {
        ErrorHandler.defaultHandler.submit(e, true);
    }
}

From source file:au.org.ala.layers.grid.GridCacheBuilder.java

private static void writeGroupGRI(File file, ArrayList<Grid> group) {
    Grid g = group.get(0);/*w  ww.  j  a v a  2  s . c  o  m*/
    RandomAccessFile[] raf = new RandomAccessFile[group.size()];
    RandomAccessFile output = null;

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

        for (int i = 0; i < group.size(); i++) {
            raf[i] = new RandomAccessFile(group.get(i).filename + ".gri", "r");
        }

        int length = g.ncols * g.nrows;
        int size = 4;
        byte[] b = new byte[size * group.size() * g.ncols];
        float noDataValue = Float.MAX_VALUE * -1;

        byte[] bi = new byte[g.ncols * 8];
        float[][] rows = new float[group.size()][g.ncols];

        for (int i = 0; i < g.nrows; i++) {
            //read
            for (int j = 0; j < raf.length; j++) {
                nextRowOfFloats(rows[j], group.get(j).datatype, group.get(j).byteorderLSB, g.ncols, raf[j], bi,
                        (float) g.nodatavalue);
            }

            //write
            ByteBuffer bb = ByteBuffer.wrap(b);
            bb.order(ByteOrder.LITTLE_ENDIAN);

            for (int k = 0; k < g.ncols; k++) {
                for (int j = 0; j < raf.length; j++) {
                    //float f = getNextValue(raf[j], group.get(j));
                    float f = rows[j][k];
                    if (Float.isNaN(f)) {
                        bb.putFloat(noDataValue);
                    } else {
                        bb.putFloat(f);
                    }
                }
            }
            output.write(b);
        }
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    } finally {
        if (output != null) {
            try {
                output.close();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
        for (int i = 0; i < raf.length; i++) {
            if (raf[i] != null) {
                try {
                    raf[i].close();
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
    }
}

From source file:com.freesundance.contacts.google.ContactsExample.java

public void listContacts() throws IOException, ServiceException, GeneralSecurityException {

    service = authenticate();//from  w w w  .  j  a v a  2 s .  c  o  m

    ContactFeed resultFeed = service.getFeed(feedUrl, ContactFeed.class);
    // Print the results
    LOG.debug(resultFeed.getTitle().getPlainText());
    for (ContactEntry entry : resultFeed.getEntries()) {
        printContact(entry);
        // Since 2.0, the photo link is always there, the presence of an actual
        // photo is indicated by the presence of an ETag.
        Link photoLink = entry.getLink("http://schemas.google.com/contacts/2008/rel#photo", "image/*");
        if (photoLink.getEtag() != null) {
            Service.GDataRequest request = service.createLinkQueryRequest(photoLink);
            request.execute();
            InputStream in = request.getResponseStream();
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            RandomAccessFile file = new RandomAccessFile("/tmp/" + entry.getSelfLink().getHref()
                    .substring(entry.getSelfLink().getHref().lastIndexOf('/') + 1), "rw");
            byte[] buffer = new byte[4096];
            for (int read = 0; (read = in.read(buffer)) != -1; out.write(buffer, 0, read)) {
            }
            file.write(out.toByteArray());
            file.close();
            in.close();
            request.end();
        }
        LOG.debug("Total: " + resultFeed.getEntries().size() + " entries found");
    }
}

From source file:com.tencent.wcdb.sample.repairdb.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Extract test database from assets.
    new AsyncTask<Void, Void, Void>() {
        @Override/*w w w  .j av  a  2  s.  c o m*/
        protected Void doInBackground(Void... params) {
            File dbFile = getDatabasePath(DBHelper.DATABASE_NAME);

            if (!dbFile.exists()) {
                dbFile.getParentFile().mkdirs();

                InputStream in = null;
                OutputStream out = null;
                try {
                    byte[] buffer = new byte[1024];
                    in = getAssets().open(DBHelper.DATABASE_NAME);
                    out = new FileOutputStream(dbFile);
                    int len;
                    while ((len = in.read(buffer)) != -1) {
                        out.write(buffer, 0, len);
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                } finally {
                    if (in != null)
                        try {
                            in.close();
                        } catch (IOException e) {
                        }
                    if (out != null)
                        try {
                            out.close();
                        } catch (IOException e) {
                        }
                }
            }
            return null;
        }
    }.execute();

    setContentView(R.layout.activity_main);

    mListView = (ListView) findViewById(R.id.list);
    mAdapter = new SimpleCursorAdapter(this, R.layout.main_listitem, null, new String[] { "a", "b" },
            new int[] { R.id.list_tv_a, R.id.list_tv_b }, 0);

    mListView.setAdapter(mAdapter);

    findViewById(R.id.btn_init_db).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new AsyncTask<Void, Void, SQLiteException>() {
                @Override
                protected void onPreExecute() {
                    mAdapter.changeCursor(null);
                }

                @Override
                protected SQLiteException doInBackground(Void... params) {
                    if (mDB != null && mDB.isOpen()) {
                        mDBHelper.close();
                        mDB = null;
                    }

                    try {
                        mDBHelper.setWriteAheadLoggingEnabled(true);
                        mDB = mDBHelper.getWritableDatabase();

                        // After successfully opened the database, backup its master info.
                        RepairKit.MasterInfo.save(mDB, mDB.getPath() + "-mbak", DBHelper.PASSPHRASE);
                    } catch (SQLiteException e) {
                        // Failed to open database, probably due to corruption.
                        mDB = null;
                        return e;
                    }

                    return null;
                }

                @Override
                protected void onPostExecute(SQLiteException e) {
                    if (e == null) {
                        // Database is successfully opened, query and refresh ListView.
                        Cursor cursor = mDB.rawQuery("SELECT rowid as _id, a, b FROM t1;", null);
                        mAdapter.changeCursor(cursor);

                        Toast.makeText(MainActivity.this, "Database is successfully opened.",
                                Toast.LENGTH_SHORT).show();
                    } else {
                        // Database could not be opened, show toast.
                        Toast.makeText(MainActivity.this,
                                "Database cannot be opened, exception: " + e.getMessage(), Toast.LENGTH_LONG)
                                .show();
                    }
                }
            }.execute();
        }
    });

    findViewById(R.id.btn_corrupt_db).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new AsyncTask<Void, Void, Exception>() {
                @Override
                protected void onPreExecute() {
                    mAdapter.changeCursor(null);
                }

                @Override
                protected Exception doInBackground(Void... params) {
                    if (mDB != null && mDB.isOpen()) {
                        mDBHelper.close();
                        mDB = null;
                    }

                    // Write random noise to the first page to corrupt the database.
                    RandomAccessFile raf = null;
                    try {
                        File dbFile = getDatabasePath(DBHelper.DATABASE_NAME);
                        raf = new RandomAccessFile(dbFile, "rw");
                        byte[] buffer = new byte[1024];
                        new Random().nextBytes(buffer);
                        raf.seek(0);
                        raf.write(buffer);
                    } catch (IOException e) {
                        return e;
                    } finally {
                        if (raf != null)
                            try {
                                raf.close();
                            } catch (IOException e) {
                            }
                    }

                    return null;
                }

                @Override
                protected void onPostExecute(Exception e) {
                    if (e == null) {
                        Toast.makeText(MainActivity.this, "Database is now CORRUPTED!", Toast.LENGTH_SHORT)
                                .show();
                    } else {
                        Toast.makeText(MainActivity.this, "Unable to overwrite database: " + e.getMessage(),
                                Toast.LENGTH_LONG).show();
                    }
                }
            }.execute();
        }
    });

    findViewById(R.id.btn_repair_db).setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            new AsyncTask<Void, Void, SQLiteException>() {
                @Override
                protected void onPreExecute() {
                    mAdapter.changeCursor(null);
                }

                @Override
                protected SQLiteException doInBackground(Void... params) {
                    if (mDB != null && mDB.isOpen()) {
                        mDBHelper.close();
                        mDB = null;
                    }

                    RepairKit.MasterInfo master = null;
                    File dbFile = getDatabasePath(DBHelper.DATABASE_NAME);
                    File masterFile = new File(dbFile.getPath() + "-mbak");
                    File newDbFile = getDatabasePath(DBHelper.DATABASE_NAME + "-recover");

                    if (masterFile.exists()) {
                        try {
                            master = RepairKit.MasterInfo.load(masterFile.getPath(), DBHelper.PASSPHRASE, null);
                        } catch (SQLiteException e) {
                            // Could not load master info. Maybe backup file itself corrupted?
                        }
                    }

                    RepairKit repair = null;
                    try {
                        repair = new RepairKit(dbFile.getPath(), // corrupted database file
                                DBHelper.PASSPHRASE, // passphrase to the database
                                DBHelper.CIPHER_SPEC, // cipher spec to the database
                                master // backup master info just loaded
                        );

                        if (newDbFile.exists())
                            newDbFile.delete();

                        SQLiteDatabase newDb = SQLiteDatabase.openOrCreateDatabase(newDbFile,
                                DBHelper.PASSPHRASE, DBHelper.CIPHER_SPEC, null, DBHelper.ERROR_HANDLER);
                        boolean result = repair.output(newDb, 0);
                        if (!result) {
                            throw new SQLiteException("Repair returns false on output.");
                        }

                        newDb.setVersion(DBHelper.DATABASE_VERSION);
                        newDb.close();
                        repair.release();
                        repair = null;

                        if (!dbFile.delete() || !newDbFile.renameTo(dbFile))
                            throw new SQLiteException("Cannot rename database.");
                    } catch (SQLiteException e) {
                        return e;
                    } finally {
                        if (repair != null)
                            repair.release();
                    }

                    return null;
                }

                @Override
                protected void onPostExecute(SQLiteException e) {
                    if (e == null) {
                        Toast.makeText(MainActivity.this, "Repair succeeded.", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MainActivity.this, "Repair failed: " + e.getMessage(), Toast.LENGTH_LONG)
                                .show();
                    }
                }
            }.execute();
        }
    });
}

From source file:org.apache.flume.channel.file.TestFileChannelRestart.java

private void doTestCorruptInflights(String name, boolean backup) throws Exception {
    Map<String, String> overrides = Maps.newHashMap();
    overrides.put(FileChannelConfiguration.USE_DUAL_CHECKPOINTS, String.valueOf(backup));
    channel = createFileChannel(overrides);
    channel.start();/*www.  j  a v a  2s  . c  o  m*/
    Assert.assertTrue(channel.isOpen());
    final Set<String> in1 = putEvents(channel, "restart-", 10, 100);
    Assert.assertEquals(100, in1.size());
    Executors.newSingleThreadScheduledExecutor().submit(new Runnable() {
        @Override
        public void run() {
            Transaction tx = channel.getTransaction();
            Set<String> out1 = takeWithoutCommit(channel, tx, 100);
            Assert.assertEquals(100, out1.size());
        }
    });
    Transaction tx = channel.getTransaction();
    Set<String> in2 = putWithoutCommit(channel, tx, "restart", 100);
    Assert.assertEquals(100, in2.size());
    forceCheckpoint(channel);
    if (backup) {
        Thread.sleep(2000);
    }
    tx.commit();
    tx.close();
    channel.stop();
    File inflight = new File(checkpointDir, name);
    RandomAccessFile writer = new RandomAccessFile(inflight, "rw");
    writer.write(new Random().nextInt());
    writer.close();
    channel = createFileChannel(overrides);
    channel.start();
    Assert.assertTrue(channel.isOpen());
    Assert.assertTrue(!backup || channel.checkpointBackupRestored());
    Set<String> out = consumeChannel(channel);
    in1.addAll(in2);
    compareInputAndOut(in1, out);
}

From source file:com.asakusafw.runtime.util.lock.LocalFileLockProvider.java

@Override
public LocalFileLockObject<T> tryLock(T target) throws IOException {
    if (baseDirectory.mkdirs() == false && baseDirectory.isDirectory() == false) {
        throw new IOException(MessageFormat.format("Failed to create lock directory: {0}", baseDirectory));
    }//from  ww w.  j  a va2 s.co m
    String fileName = String.format("%08x.lck", target == null ? -1 : target.hashCode()); //$NON-NLS-1$
    File lockFile = new File(baseDirectory, fileName);
    RandomAccessFile fd = new RandomAccessFile(lockFile, "rw"); //$NON-NLS-1$
    boolean success = false;
    try {
        if (LOG.isDebugEnabled()) {
            LOG.debug(MessageFormat.format("Start to acquire lock for \"{0}\" ({1})", //$NON-NLS-1$
                    target, lockFile));
        }
        FileLock lockEntity = getLock(target, lockFile, fd);
        if (lockEntity == null) {
            return null;
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug(MessageFormat.format("Finished to acquire lock for \"{0}\" ({1})", //$NON-NLS-1$
                        target, lockFile));
            }
            try {
                fd.seek(0L);
                fd.setLength(0L);
                fd.write(String.valueOf(target).getBytes(ENCODING));
                success = true;
                return new LocalFileLockObject<>(target, lockFile, fd, lockEntity);
            } finally {
                if (success == false) {
                    lockEntity.release();
                }
            }
        }
    } finally {
        if (success == false) {
            fd.close();
        }
    }
}

From source file:org.wso2.msf4j.internal.router.HttpServerTest.java

protected void testStreamUpload(int size) throws IOException {
    //create a random file to be uploaded.
    File fname = tmpFolder.newFile();
    RandomAccessFile randf = new RandomAccessFile(fname, "rw");
    String contentStr = IntStream.range(0, size).mapToObj(value -> String.valueOf((int) (Math.random() * 1000)))
            .collect(Collectors.joining(""));
    randf.write(contentStr.getBytes(Charsets.UTF_8));
    randf.close();//w w w.j  a v  a2s.  com

    //test stream upload
    HttpURLConnection urlConn = request("/test/v1/stream/upload", HttpMethod.PUT);
    Files.copy(fname, urlConn.getOutputStream());
    Assert.assertEquals(200, urlConn.getResponseCode());
    String contentFromServer = getContent(urlConn);
    Assert.assertEquals(contentStr, contentFromServer);
    urlConn.disconnect();
}

From source file:org.kchine.rpf.PoolUtils.java

public static void killLocalWinProcess(String processId, boolean isKILLSIG) throws Exception {

    String killpath = System.getProperty("java.io.tmpdir") + "/rpf/WinTools/" + "kill.exe";
    File killFile = new File(killpath);
    if (!killFile.exists()) {
        killFile.getParentFile().mkdirs();
        InputStream is = PoolUtils.class.getResourceAsStream("/wintools/kill.exe");
        RandomAccessFile raf = new RandomAccessFile(killFile, "rw");
        raf.setLength(0);/*from ww w  .  ja va 2  s  .c o  m*/
        int b;
        while ((b = is.read()) != -1)
            raf.write((byte) b);
        raf.close();
    }
    String[] command = new String[] { killpath, processId };
    Runtime rt = Runtime.getRuntime();
    final Process proc = rt.exec(command);

    final StringBuffer killPrint = new StringBuffer();
    final StringBuffer errorPrint = new StringBuffer();
    new Thread(new Runnable() {
        public void run() {
            try {
                InputStream is = proc.getInputStream();
                int b;
                while ((b = is.read()) != -1) {
                    killPrint.append((char) b);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }).start();
    new Thread(new Runnable() {
        public void run() {
            try {
                InputStream is = proc.getErrorStream();
                int b;
                while ((b = is.read()) != -1) {
                    errorPrint.append((char) b);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }).start();

    int exitVal = proc.waitFor();
    if (exitVal != 0)
        throw new Exception("kill exit code : " + exitVal + "\n" + errorPrint);
}

From source file:org.apache.flume.channel.file.TestFileChannelRestart.java

@Test
public void testCorruptCheckpointVersionMostSignificant4Bytes() throws Exception {
    Map<String, String> overrides = Maps.newHashMap();
    channel = createFileChannel(overrides);
    channel.start();//from  w  w  w.j av a2s  .c  om
    Assert.assertTrue(channel.isOpen());
    Set<String> in = putEvents(channel, "restart", 10, 100);
    Assert.assertEquals(100, in.size());
    forceCheckpoint(channel);
    channel.stop();
    File checkpoint = new File(checkpointDir, "checkpoint");
    RandomAccessFile writer = new RandomAccessFile(checkpoint, "rw");
    writer.seek(EventQueueBackingStoreFile.INDEX_VERSION * Serialization.SIZE_OF_LONG);
    writer.write(new byte[] { (byte) 1, (byte) 5 });
    writer.getFD().sync();
    writer.close();
    channel = createFileChannel(overrides);
    channel.start();
    Assert.assertTrue(channel.isOpen());
    Set<String> out = consumeChannel(channel);
    Assert.assertTrue(channel.didFullReplayDueToBadCheckpointException());
    compareInputAndOut(in, out);
}