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.jk.framework.util.FakeRunnable.java

/**
 * Write on file.//  w w w .j  a  v  a  2  s. co  m
 *
 * @author Mohamde Kiswani
 * @param file
 *            the file
 * @param string
 *            the string
 * @param lineIndex
 *            the line index
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @since 28-1-2010
 * @description : to write on file by using random access ssechanism
 */
public static void writeOnFile(final File file, final String string, final long lineIndex) throws IOException {
    final RandomAccessFile rand = new RandomAccessFile(file, "rw");
    rand.seek(lineIndex); // Seek to lineIndex of file
    rand.writeBytes(string); // Write end of file
    rand.close();
}

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

private void overrideWithGarbage(SSTableReader sstable, long startPosition, long endPosition)
        throws IOException {
    RandomAccessFile file = new RandomAccessFile(sstable.getFilename(), "rw");
    file.seek(startPosition);/* ww w  . jav a  2  s.c o  m*/
    file.writeBytes(StringUtils.repeat('z', (int) (endPosition - startPosition)));
    file.close();
}

From source file:org.apache.hadoop.hive.ql.io.TestRCFile.java

@Test
public void testReadCorruptFile() throws IOException, SerDeException {
    cleanup();/*from   ww w.jav a2 s. c om*/

    byte[][] record = { null, null, null, null, null, null, null, null };

    RCFileOutputFormat.setColumnNumber(conf, expectedFieldsData.length);
    RCFile.Writer writer = new RCFile.Writer(fs, conf, file, null, new DefaultCodec());
    BytesRefArrayWritable bytes = new BytesRefArrayWritable(record.length);
    final int recCount = 100;
    Random rand = new Random();
    for (int recIdx = 0; recIdx < recCount; recIdx++) {
        for (int i = 0; i < record.length; i++) {
            record[i] = new Integer(rand.nextInt()).toString().getBytes("UTF-8");
        }
        for (int i = 0; i < record.length; i++) {
            BytesRefWritable cu = new BytesRefWritable(record[i], 0, record[i].length);
            bytes.set(i, cu);
        }
        writer.append(bytes);
        bytes.clear();
    }
    writer.close();

    // Insert junk in middle of file. Assumes file is on local disk.
    RandomAccessFile raf = new RandomAccessFile(file.toUri().getPath(), "rw");
    long corruptOffset = raf.length() / 2;
    LOG.info("corrupting " + raf + " at offset " + corruptOffset);
    raf.seek(corruptOffset);
    raf.writeBytes("junkjunkjunkjunkjunkjunkjunkjunk");
    raf.close();

    // Set the option for tolerating corruptions. The read should succeed.
    Configuration tmpConf = new Configuration(conf);
    tmpConf.setBoolean("hive.io.rcfile.tolerate.corruptions", true);
    RCFile.Reader reader = new RCFile.Reader(fs, file, tmpConf);

    LongWritable rowID = new LongWritable();

    while (true) {
        boolean more = reader.next(rowID);
        if (!more) {
            break;
        }
        BytesRefArrayWritable cols = new BytesRefArrayWritable();
        reader.getCurrentRow(cols);
        cols.resetValid(8);
    }

    reader.close();
}

From source file:org.apache.james.mailrepository.file.MBoxMailRepository.java

/**
 * @see org.apache.james.mailrepository.api.MailRepository#store(Mail)
 *//*  ww w  .  j a  v a2 s  .c  o  m*/
public void store(Mail mc) {

    if ((getLogger().isDebugEnabled())) {
        String logBuffer = this.getClass().getName() + " Will store message to file " + mboxFile;

        getLogger().debug(logBuffer);
    }
    this.mList = null;
    // Now make up the from header
    String fromHeader = null;
    String message = null;
    try {
        message = getRawMessage(mc.getMessage());
        // check for nullsender
        if (mc.getMessage().getFrom() == null) {
            fromHeader = "From   " + dy.format(Calendar.getInstance().getTime());
        } else {
            fromHeader = "From " + mc.getMessage().getFrom()[0] + " "
                    + dy.format(Calendar.getInstance().getTime());
        }

    } catch (IOException e) {
        getLogger().error("Unable to parse mime message for " + mboxFile, e);
    } catch (MessagingException e) {
        getLogger().error("Unable to parse mime message for " + mboxFile, e);
    }
    // And save only the new stuff to disk
    RandomAccessFile saveFile;
    try {
        saveFile = new RandomAccessFile(mboxFile, "rw");
        saveFile.seek(saveFile.length()); // Move to the end
        saveFile.writeBytes((fromHeader + "\n"));
        saveFile.writeBytes((message + "\n"));
        saveFile.close();

    } catch (FileNotFoundException e) {
        getLogger().error("Unable to save(open) file (File not found) " + mboxFile, e);
    } catch (IOException e) {
        getLogger().error("Unable to write file (General I/O problem) " + mboxFile, e);
    }
}

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

protected void writeCorruptedData(RandomAccessFile file) throws IOException {
    final String messageForPreUpgradeVersion = "\nThis file is INTENTIONALLY CORRUPTED so that versions\n"
            + "of Hadoop prior to 0.13 (which are incompatible\n"
            + "with this directory layout) will fail to start.\n";

    file.seek(0);/*  ww w  .  ja v  a2s .c om*/
    file.writeInt(FSConstants.LAYOUT_VERSION);
    org.apache.hadoop.io.UTF8.writeString(file, "");
    file.writeBytes(messageForPreUpgradeVersion);
    file.getFD().sync();
}

From source file:org.apache.jxtadoop.hdfs.server.common.Storage.java

protected void writeCorruptedData(RandomAccessFile file) throws IOException {
    final String messageForPreUpgradeVersion = "\nThis file is INTENTIONALLY CORRUPTED so that versions\n"
            + "of Hadoop prior to 0.13 (which are incompatible\n"
            + "with this directory layout) will fail to start.\n";

    file.seek(0);/*from  w  w  w  .j  a v  a2  s.co  m*/
    file.writeInt(FSConstants.LAYOUT_VERSION);
    org.apache.jxtadoop.io.UTF8.writeString(file, "");
    file.writeBytes(messageForPreUpgradeVersion);
    file.getFD().sync();
}

From source file:com.stimulus.archiva.domain.Volume.java

protected void writeVolumeInfoLines(RandomAccessFile out) {
    try {/*from   w w w .j  av a  2  s  .c o  m*/
        logger.debug("writeVolumeInfoLines()");
        out.setLength(0);
        out.seek(0);
        // don't save to ejected volume
        if (isEjected())
            return;

        // make a new volume unused
        if (getStatus() == Volume.Status.NEW)
            setStatus(Volume.Status.UNUSED);
        out.seek(0); //Seek to end of file
        out.writeBytes("# Archiva " + Config.getConfig().getApplicationVersion() + " Volume Information\n");
        out.writeBytes("# note: this file is crucial - do not delete it!\n");
        out.writeBytes("version:3\n");
        if (getID() != null || getID().length() > 0) {
            out.writeBytes("id:" + getID() + "\n");
        }
        if (getStatus() != null) {
            out.writeBytes("status:" + getStatus() + "\n");
        }
        if (getCreatedDate() != null)
            out.writeBytes("created:" + DateUtil.convertDatetoString(getCreatedDate()) + "\n");
        if (getClosedDate() != null)
            out.writeBytes("closed:" + DateUtil.convertDatetoString(getClosedDate()) + "\n");

    } catch (IOException io) {
        if (getStatus() != Volume.Status.UNMOUNTED)
            logger.error("failed to write volumeinfo. {" + toString() + "} cause:" + io, io);
    } catch (ConfigurationException ce) {
        logger.error("failed to set volume status. {" + toString() + "} cause:" + ce, ce);
    }
}

From source file:captureplugin.CapturePlugin.java

/**
 * Check the programs after data update.
 *//*from  w  w  w . j a va 2 s .c  o m*/
public void handleTvDataUpdateFinished() {
    mNeedsUpdate = true;

    if (mAllowedToShowDialog) {
        mNeedsUpdate = false;

        DeviceIf[] devices = mConfig.getDeviceArray();

        final DefaultTableModel model = new DefaultTableModel() {
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };

        model.setColumnCount(5);
        model.setColumnIdentifiers(new String[] { mLocalizer.msg("device", "Device"),
                Localizer.getLocalization(Localizer.I18N_CHANNEL), mLocalizer.msg("date", "Date"),
                ProgramFieldType.START_TIME_TYPE.getLocalizedName(),
                ProgramFieldType.TITLE_TYPE.getLocalizedName() });

        JTable table = new JTable(model);
        table.getTableHeader().setReorderingAllowed(false);
        table.getTableHeader().setResizingAllowed(false);
        table.getColumnModel().getColumn(0).setCellRenderer(new DefaultTableCellRenderer() {
            public Component getTableCellRendererComponent(JTable renderTable, Object value, boolean isSelected,
                    boolean hasFocus, int row, int column) {
                Component c = super.getTableCellRendererComponent(renderTable, value, isSelected, hasFocus, row,
                        column);

                if (value instanceof DeviceIf) {
                    if (((DeviceIf) value).getDeleteRemovedProgramsAutomatically() && !isSelected) {
                        c.setForeground(Color.red);
                    }
                }

                return c;
            }
        });

        int[] columnWidth = new int[5];

        for (int i = 0; i < columnWidth.length; i++) {
            columnWidth[i] = UiUtilities.getStringWidth(table.getFont(), model.getColumnName(i)) + 10;
        }

        for (DeviceIf device : devices) {
            Program[] deleted = device.checkProgramsAfterDataUpdateAndGetDeleted();

            if (deleted != null && deleted.length > 0) {
                for (Program p : deleted) {
                    if (device.getDeleteRemovedProgramsAutomatically() && !p.isExpired() && !p.isOnAir()) {
                        device.remove(UiUtilities.getLastModalChildOf(getParentFrame()), p);
                    } else {
                        device.removeProgramWithoutExecution(p);
                    }

                    if (!p.isExpired()) {
                        Object[] o = new Object[] { device, p.getChannel().getName(), p.getDateString(),
                                p.getTimeString(), p.getTitle() };

                        for (int i = 0; i < columnWidth.length; i++) {
                            columnWidth[i] = Math.max(columnWidth[i],
                                    UiUtilities.getStringWidth(table.getFont(), o[i].toString()) + 10);
                        }

                        model.addRow(o);
                    }
                }
            }

            device.getProgramList();
        }

        if (model.getRowCount() > 0) {
            int sum = 0;

            for (int i = 0; i < columnWidth.length; i++) {
                table.getColumnModel().getColumn(i).setPreferredWidth(columnWidth[i]);

                if (i < columnWidth.length - 1) {
                    table.getColumnModel().getColumn(i).setMaxWidth(columnWidth[i]);
                }

                sum += columnWidth[i];
            }

            JScrollPane scrollPane = new JScrollPane(table);
            scrollPane.setPreferredSize(new Dimension(450, 250));

            if (sum > 500) {
                table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
                scrollPane.getViewport().setPreferredSize(
                        new Dimension(sum, scrollPane.getViewport().getPreferredSize().height));
            }

            JButton export = new JButton(mLocalizer.msg("exportList", "Export list"));
            export.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    JFileChooser chooser = new JFileChooser();
                    chooser.setDialogType(JFileChooser.SAVE_DIALOG);
                    chooser.setFileFilter(new FileFilter() {
                        public boolean accept(File f) {
                            return f.isDirectory() || f.toString().toLowerCase().endsWith(".txt");
                        }

                        public String getDescription() {
                            return "*.txt";
                        }
                    });

                    chooser.setSelectedFile(new File("RemovedPrograms.txt"));
                    if (chooser.showSaveDialog(
                            UiUtilities.getLastModalChildOf(getParentFrame())) == JFileChooser.APPROVE_OPTION) {
                        if (chooser.getSelectedFile() != null) {
                            String file = chooser.getSelectedFile().getAbsolutePath();

                            if (!file.toLowerCase().endsWith(".txt") && file.indexOf('.') == -1) {
                                file = file + ".txt";
                            }

                            if (file.indexOf('.') != -1) {
                                try {
                                    RandomAccessFile write = new RandomAccessFile(file, "rw");
                                    write.setLength(0);

                                    String eolStyle = File.separator.equals("/") ? "\n" : "\r\n";

                                    for (int i = 0; i < model.getRowCount(); i++) {
                                        StringBuilder line = new StringBuilder();

                                        for (int j = 0; j < model.getColumnCount(); j++) {
                                            line.append(model.getValueAt(i, j)).append(' ');
                                        }

                                        line.append(eolStyle);

                                        write.writeBytes(line.toString());
                                    }

                                    write.close();
                                } catch (Exception ee) {
                                }
                            }
                        }
                    }
                }
            });

            Object[] message = {
                    mLocalizer.msg("deletedText",
                            "The data was changed and the following programs were deleted:"),
                    scrollPane, export };

            JOptionPane pane = new JOptionPane();
            pane.setMessage(message);
            pane.setMessageType(JOptionPane.PLAIN_MESSAGE);

            final JDialog d = pane.createDialog(UiUtilities.getLastModalChildOf(getParentFrame()),
                    mLocalizer.msg("CapturePlugin", "CapturePlugin") + " - "
                            + mLocalizer.msg("deletedTitle", "Deleted programs"));
            d.setResizable(true);
            d.setModal(false);

            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    d.setVisible(true);
                }
            });
        }
    }
}

From source file:com.sun.faban.harness.webclient.ResultAction.java

private String editResultInfo(String runID) throws FileNotFoundException, IOException {
    RunId runId = new RunId(runID);
    String ts = null;/*from ww w  .  j a  v  a 2 s  .  c  om*/
    String[] status = new String[2];
    File file = new File(Config.OUT_DIR + runID + '/' + Config.RESULT_INFO);
    RandomAccessFile rf = new RandomAccessFile(file, "rwd");
    long size = rf.length();
    byte[] buffer = new byte[(int) size];
    rf.readFully(buffer);
    String content = new String(buffer, 0, (int) size);
    int idx = content.indexOf('\t');
    if (idx != -1) {
        status[0] = content.substring(0, idx).trim();
        status[1] = content.substring(++idx).trim();
    } else {
        status[0] = content.trim();
        int lastIdxln = status[0].lastIndexOf("\n");
        if (lastIdxln != -1)
            status[0] = status[0].substring(0, lastIdxln - 1);
    }
    if (status[1] != null) {
        ts = status[1];
    } else {
        String paramFileName = runId.getResultDir().getAbsolutePath() + File.separator + "run.xml";
        File paramFile = new File(paramFileName);
        long dt = paramFile.lastModified();
        ts = dateFormat.format(new Date(dt));
        rf.seek(rf.length());
        rf.writeBytes('\t' + ts.trim());
    }
    rf.close();
    return ts;
}

From source file:org.apache.james.mailrepository.file.MBoxMailRepository.java

/**
 * @see org.apache.james.mailrepository.api.MailRepository#remove(Collection)
 *///  w  w  w  .  j a v  a2s . co  m
public void remove(final Collection<Mail> mails) {
    if ((getLogger().isDebugEnabled())) {
        String logBuffer = this.getClass().getName() + " Removing entry for key " + mails;

        getLogger().debug(logBuffer);
    }
    // The plan is as follows:
    // Attempt to locate the message in the file
    // by reading through the
    // once we've done that then seek to the file
    try {
        RandomAccessFile ins = new RandomAccessFile(mboxFile, "r"); // The
                                                                    // source
        final RandomAccessFile outputFile = new RandomAccessFile(mboxFile + WORKEXT, "rw"); // The
                                                                                            // destination
        parseMboxFile(ins, new MessageAction() {
            public boolean isComplete() {
                return false;
            }

            public MimeMessage messageAction(String messageSeparator, String bodyText, long messageStart) {
                // Write out the messages as we go, until we reach the key
                // we want
                try {
                    String currentKey = generateKeyValue(bodyText);
                    boolean foundKey = false;
                    Iterator<Mail> mailList = mails.iterator();
                    String key;
                    while (mailList.hasNext()) {
                        // Attempt to find the current key in the array
                        key = mailList.next().getName();
                        if (key.equals(currentKey)) {
                            // Don't write the message to disk
                            foundKey = true;
                            break;
                        }
                    }
                    if (!foundKey) {
                        // We didn't find the key in the array so we will
                        // keep it
                        outputFile.writeBytes(messageSeparator + "\n");
                        outputFile.writeBytes(bodyText);

                    }
                } catch (NoSuchAlgorithmException e) {
                    getLogger().error("MD5 not supported! ", e);
                } catch (IOException e) {
                    getLogger().error("Unable to write file (General I/O problem) " + mboxFile, e);
                }
                return null;
            }
        });
        ins.close();
        outputFile.close();
        // Delete the old mbox file
        File mbox = new File(mboxFile);
        FileUtils.forceDelete(mbox);
        // And rename the lock file to be the new mbox
        mbox = new File(mboxFile + WORKEXT);
        if (!mbox.renameTo(new File(mboxFile))) {
            throw new IOException("Failed to rename file " + mbox + " -> " + mboxFile);
        }

        // Now delete the keys in mails from the main hash
        Iterator<Mail> mailList = mails.iterator();
        String key;
        while (mailList.hasNext()) {
            // Attempt to find the current key in the array
            key = mailList.next().getName();
            mList.remove(key);
        }

    } catch (FileNotFoundException e) {
        getLogger().error("Unable to save(open) file (File not found) " + mboxFile, e);
    } catch (IOException e) {
        getLogger().error("Unable to write file (General I/O problem) " + mboxFile, e);
    }
}