Example usage for java.io RandomAccessFile read

List of usage examples for java.io RandomAccessFile read

Introduction

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

Prototype

public int read(byte b[]) throws IOException 

Source Link

Document

Reads up to b.length bytes of data from this file into an array of bytes.

Usage

From source file:org.opencms.workplace.tools.sites.CmsSiteFaviconDialog.java

/**
 * @see org.opencms.workplace.administration.A_CmsImportFromHttp#actionCommit()
 *//*from w w w  . ja va2  s.co  m*/
@Override
public void actionCommit() throws IOException, ServletException {

    String site = getParamSites();
    try {
        // check if the site stored in the sites parameter exists and is readable
        CmsObject cms = OpenCms.initCmsObject(getCms());
        cms.getRequestContext().setSiteRoot("");
        cms.existsResource(site + "/");

        // copy the file to the server
        copyFileToServer(OpenCms.getSystemInfo().getPackagesRfsPath());
        if ((getParamImportfile() == null) || !getParamImportfile().equals(ICON_NAME)) {
            // file null or name not valid
            throw new CmsException(
                    Messages.get().container(Messages.ERR_INVALID_FAVICON_FILE_1, getParamImportfile()));
        }

        // get the uploaded file content
        String importpath = OpenCms.getSystemInfo().getPackagesRfsPath();
        importpath = OpenCms.getSystemInfo()
                .getAbsoluteRfsPathRelativeToWebInf(importpath + getParamImportfile());
        RandomAccessFile f = new RandomAccessFile(importpath, "r");
        byte[] content = new byte[(int) f.length()];
        f.read(content);
        f.close();

        // check the existence of favicon
        String favCreatePath = site + "/" + ICON_NAME;
        int imageResId = CmsResourceTypeImage.getStaticTypeId();
        if (cms.existsResource(favCreatePath)) {
            // replace the existing favicon
            cms.lockResource(favCreatePath);
            cms.replaceResource(favCreatePath, imageResId, content, new ArrayList<CmsProperty>());
            cms.unlockResource(favCreatePath);
        } else {
            // create the new favicon
            cms.createResource(favCreatePath, imageResId, content, new ArrayList<CmsProperty>());
        }

        // set the dialog parameters
        String title = OpenCms.getSiteManager().getSiteForSiteRoot(site).getTitle();
        Map<String, String[]> params = new HashMap<String, String[]>();
        params.put(CmsSitesOverviewList.PARAM_SITES, new String[] { getParamSites() });
        params.put(CmsSitesOverviewList.PARAM_SITE_TITLE, new String[] { title });
        params.put(PARAM_ACTION, new String[] { DIALOG_INITIAL });

        // forward the request
        getToolManager().jspForwardTool(this, "/sites/detail", params);

    } catch (CmsException e) {
        // error copying the file to the OpenCms server
        if (LOG.isErrorEnabled()) {
            LOG.error(e.getLocalizedMessage(getLocale()), e);
        }
        setException(e);
        return;
    }
}

From source file:com.polarion.pso.license.FetchUserLicenseTypeServlet.java

@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    ISecurityService securityService = (ISecurityService) PlatformContext.getPlatform()
            .lookupService(ISecurityService.class);
    ITrackerService trackerService = (ITrackerService) PlatformContext.getPlatform()
            .lookupService(ITrackerService.class);

    String userId = securityService.getCurrentUser();
    String userName = trackerService.getTrackerUser(userId).getName();

    long cutoff = System.currentTimeMillis() - (1000);
    File directory = new File("./logs/main");

    FileFilter wcFilter = new WildcardFileFilter("log4j-licensing-*.log");
    AgeFileFilter ageFilter = new AgeFileFilter(cutoff);
    FileFilter andFilter = new org.apache.commons.io.filefilter.AndFileFilter((IOFileFilter) ageFilter,
            (IOFileFilter) wcFilter);//from   w  w  w.j ava  2 s.c om

    Collection<File> matches = FileUtils.listFiles(directory, (IOFileFilter) andFilter, null);

    if (!matches.isEmpty()) {

        File myFile = matches.iterator().next();
        RandomAccessFile licFile = new RandomAccessFile(myFile, "r");

        // Read the last 1024 bytes
        Long fileLength = licFile.length();
        Long offSet = fileLength - 1024;
        byte[] bStr = new byte[1024];
        licFile.seek(offSet);
        licFile.read(bStr);
        licFile.close();

        String logString = new java.lang.String(bStr);

        String[] lineArray = logString.split("\n");

        String searchString = "INFO  PolarionLicensing  - User \'" + userId + "\' logged in";
        Boolean found = false;
        Integer size = lineArray.length - 1;
        String licType = directory.toString();

        for (int i = size; i >= 0; i--) {
            String line = lineArray[i];
            if (line.contains(searchString) && found == false) {
                found = true;
                i = -1;
                Integer startIndex = line.indexOf(searchString) + searchString.length() + 6;
                licType = line.substring(startIndex);
                licType = licType.replace("\r", "");
                licType = licType.trim();
            }
        }

        req.setAttribute("userId", userName);
        req.setAttribute("licType", licType);
    } else {
        req.setAttribute("userId", userName);
        req.setAttribute("licType", "Not Found");
    }

    getServletContext().getRequestDispatcher("/currentUserLicenseType.jsp").forward(req, resp);
}

From source file:com.puppycrawl.tools.checkstyle.checks.NewlineAtEndOfFileCheck.java

/**
 * Checks whether the content provided by the Reader ends with the platform
 * specific line separator.//from w  w w  .  j  a va 2 s  .  co  m
 * @param randomAccessFile The reader for the content to check
 * @return boolean Whether the content ends with a line separator
 * @throws IOException When an IO error occurred while reading from the
 *         provided reader
 */
private boolean endsWithNewline(RandomAccessFile randomAccessFile) throws IOException {
    final int len = lineSeparator.length();
    if (randomAccessFile.length() < len) {
        return false;
    }
    randomAccessFile.seek(randomAccessFile.length() - len);
    final byte[] lastBytes = new byte[len];
    final int readBytes = randomAccessFile.read(lastBytes);
    if (readBytes != len) {
        throw new IOException("Unable to read " + len + " bytes, got " + readBytes);
    }
    return lineSeparator.matches(lastBytes);
}

From source file:org.apache.hadoop.io.TestIOUtils.java

@Test
public void testWriteFully() throws IOException {
    final int INPUT_BUFFER_LEN = 10000;
    final int HALFWAY = 1 + (INPUT_BUFFER_LEN / 2);
    byte[] input = new byte[INPUT_BUFFER_LEN];
    for (int i = 0; i < input.length; i++) {
        input[i] = (byte) (i & 0xff);
    }/*from  w w  w  .  ja  va 2  s  . c om*/
    byte[] output = new byte[input.length];

    try {
        RandomAccessFile raf = new RandomAccessFile(TEST_FILE_NAME, "rw");
        FileChannel fc = raf.getChannel();
        ByteBuffer buf = ByteBuffer.wrap(input);
        IOUtils.writeFully(fc, buf);
        raf.seek(0);
        raf.read(output);
        for (int i = 0; i < input.length; i++) {
            assertEquals(input[i], output[i]);
        }
        buf.rewind();
        IOUtils.writeFully(fc, buf, HALFWAY);
        for (int i = 0; i < HALFWAY; i++) {
            assertEquals(input[i], output[i]);
        }
        raf.seek(0);
        raf.read(output);
        for (int i = HALFWAY; i < input.length; i++) {
            assertEquals(input[i - HALFWAY], output[i]);
        }
    } finally {
        File f = new File(TEST_FILE_NAME);
        if (f.exists()) {
            f.delete();
        }
    }
}

From source file:com.ibm.watson.developer_cloud.android.text_to_speech.v1.TTSUtility.java

private byte[] analyzeOpusData(InputStream is) {
    String inFilePath = getBaseDir() + "Watson.opus";
    String outFilePath = getBaseDir() + "Watson.pcm";
    File inFile = new File(inFilePath);
    File outFile = new File(outFilePath);
    outFile.deleteOnExit();/*from   w  w  w.j  a  va2  s .  c  om*/
    inFile.deleteOnExit();

    try {
        RandomAccessFile inRaf = new RandomAccessFile(inFile, "rw");
        byte[] opus = IOUtils.toByteArray(is);
        inRaf.write(opus);

        sampleRate = OggOpus.decode(inFilePath, outFilePath, sampleRate); // zero means to detect the sample rate by decoder

        RandomAccessFile outRaf = new RandomAccessFile(outFile, "r");

        byte[] data = new byte[(int) outRaf.length()];

        int outLength = outRaf.read(data);

        inRaf.close();
        outRaf.close();
        if (outLength == 0) {
            throw new IOException("Data reading failed");
        }
        return data;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return new byte[0];
}

From source file:dbseer.comp.process.live.LogTailer.java

/**
 * Read new lines.//from w ww. j  ava  2  s  .co m
 *
 * @param reader The file to read
 * @return The new position after the lines have been read
 * @throws java.io.IOException if an I/O error occurs.
 */
private long readLines(RandomAccessFile reader) throws IOException {
    StringBuilder sb = new StringBuilder();

    long pos = reader.getFilePointer();
    long rePos = pos; // position to re-read

    int num;
    boolean seenCR = false;
    while (run && ((num = reader.read(inbuf)) != -1)) {
        for (int i = 0; i < num; i++) {
            byte ch = inbuf[i];
            switch (ch) {
            case '\n':
                seenCR = false; // swallow CR before LF
                listener.handle(sb.toString(), pos + i + 1);
                sb.setLength(0);
                rePos = pos + i + 1;
                break;
            case '\r':
                if (seenCR) {
                    sb.append('\r');
                }
                seenCR = true;
                break;
            default:
                if (seenCR) {
                    seenCR = false; // swallow final CR
                    listener.handle(sb.toString(), pos + i + 1);
                    sb.setLength(0);
                    rePos = pos + i + 1;
                }
                sb.append((char) ch); // add character, not its ascii value
            }
        }

        pos = reader.getFilePointer();
    }

    reader.seek(rePos); // Ensure we can re-read if necessary
    return rePos;
}

From source file:nl.mpi.handle.util.implementation.HandleUtil.java

/**
 * Gets the website service account private key file from the local file system.
 * @return Returns the private key file as a byte array.
 * @throws java.io.FileNotFoundException Throws <CODE>FileNotFoundException</CODE> if the private key file for the website Handle System service account cannot be found on the local file system.
 * @throws java.io.IOException Throws <CODE>IOException</CODE> if the private key file for the website Handle System service account cannot be accessed.
 *//*w ww . j ava2s  .co m*/
public byte[] getPrivateKeyFile() throws IOException {
    byte[] fileBytes = null;

    File privKeyFile = new File(handleAdminKeyFilePath);

    if (privKeyFile.exists() == false) {
        throw new IOException("The admin private key file could not be found.");
    }

    if (privKeyFile.canRead() == false) {
        throw new IOException("The admin private key file cannot be read.");
    }

    RandomAccessFile privateKeyContents = new RandomAccessFile(privKeyFile, "r");

    int length = (int) privateKeyContents.length();

    if (length > 0) {
        fileBytes = new byte[length];
        privateKeyContents.read(fileBytes);
        privateKeyContents.close();
    } else {
        throw new IOException("The private key file is empty.");
    }

    return fileBytes;
}

From source file:com.ieasy.basic.util.file.FileUtils.java

/**
 * ??/*from   w w w  .  j a  v a 2s  .co m*/
 * 
 * @param fileName
 *            ??
 */
public static void readFileByRandomAccess(String fileName) {
    RandomAccessFile randomFile = null;
    try {
        System.out.println("??");
        // ????
        randomFile = new RandomAccessFile(fileName, "r");
        // 
        long fileLength = randomFile.length();
        // ?
        int beginIndex = (fileLength > 4) ? 4 : 0;
        // ?beginIndex?
        randomFile.seek(beginIndex);
        byte[] bytes = new byte[10];
        int byteread = 0;
        // 10?10
        // ?byteread
        while ((byteread = randomFile.read(bytes)) != -1) {
            System.out.write(bytes, 0, byteread);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (randomFile != null) {
            try {
                randomFile.close();
            } catch (IOException e1) {
            }
        }
    }
}

From source file:phex.update.UpdateCheckRunner.java

private String getErrorLogFileTail() {
    try {/*w  w w . ja v  a 2 s .com*/
        File logFile = Environment.getInstance().getPhexConfigFile("phex.error.log");
        if (!logFile.exists()) {
            return null;
        }
        RandomAccessFile raf = new RandomAccessFile(logFile, "r");
        long pos = Math.max(raf.length() - 10 * 1024, 0);
        raf.seek(pos);
        byte[] buffer = new byte[(int) Math.min(10 * 1024, raf.length())];
        int lenRead = raf.read(buffer);
        return new String(buffer, 0, lenRead);
    } catch (IOException exp) {
        NLogger.error(UpdateCheckRunner.class, exp, exp);
        return exp.toString();
    }
}

From source file:TarList.java

public TarEntry(RandomAccessFile is) throws IOException, TarException {

    fileOffset = is.getFilePointer();/*w  w w. ja v  a2  s  .  c  o  m*/

    // read() returns -1 at EOF
    if (is.read(name) < 0)
        throw new EOFException();
    // Tar pads to block boundary with nulls.
    if (name[0] == '\0')
        throw new EOFException();
    // OK, read remaining fields.
    is.read(mode);
    is.read(uid);
    is.read(gid);
    is.read(size);
    is.read(mtime);
    is.read(chksum);
    type = is.readByte();
    is.read(linkName);
    is.read(magic);
    is.read(uname);
    is.read(gname);
    is.read(devmajor);
    is.read(devminor);

    // Since the tar header is < 512, we need to skip it.
    is.skipBytes((int) (TarFile.RECORDSIZE - (is.getFilePointer() % TarFile.RECORDSIZE)));

    // TODO if checksum() fails,
    //   throw new TarException("Failed to find next header");

}