List of usage examples for java.io RandomAccessFile length
public native long length() throws IOException;
From source file:org.socialnetlib.android.AppdotnetApi.java
private static byte[] readFile(File file) throws IOException { // Open file//from w w w. j a v a 2s . c om RandomAccessFile f = new RandomAccessFile(file, "r"); try { // Get and check length long longlength = f.length(); int length = (int) longlength; if (length != longlength) throw new IOException("File size >= 2 GB"); // Read file and return data byte[] data = new byte[length]; f.readFully(data); return data; } finally { f.close(); } }
From source file:eionet.eunis.servlets.DownloadServlet.java
/** * Copy the given byte range of the given input to the given output. * * @param input The input to copy the given range to the given output for. * @param output The output to copy the given range from the given input for. * @param start Start of the byte range. * @param length Length of the byte range. * @throws IOException If something fails at I/O level. *//*from ww w. j av a 2 s.c o m*/ private static void copy(RandomAccessFile input, OutputStream output, long start, long length) throws IOException { byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; int read; if (input.length() == length) { // Write full range. while ((read = input.read(buffer)) > 0) { output.write(buffer, 0, read); } } else { // Write partial range. input.seek(start); long toRead = length; while ((read = input.read(buffer)) > 0) { toRead = toRead - read; if (toRead > 0) { output.write(buffer, 0, read); } else { output.write(buffer, 0, (int) toRead + read); break; } } } }
From source file:org.gcaldaemon.core.sendmail.SendMail.java
private static final String readContent(RandomAccessFile raf) throws Exception { String content = null;/*from w ww.ja v a2s . c o m*/ int len = Math.min((int) raf.length(), 500); byte[] bytes = new byte[len]; raf.seek(0); raf.readFully(bytes); if (bytes[0] == -17 && bytes[1] == -69 && bytes[2] == -65) { // UTF-8 header found log.debug("File encoding is 'UTF-8'."); bytes = new byte[(int) raf.length() - 3]; raf.seek(3); raf.readFully(bytes); content = StringUtils.decodeToString(bytes, StringUtils.UTF_8).trim(); } else { // Autodetect encoding String header = StringUtils.decodeToString(bytes, StringUtils.US_ASCII).toUpperCase().replace(':', '='); String encoding = null; int pos = header.indexOf("ENCODING="); if (pos != -1) { int end = endOf(header, pos + 10); if (end != -1) { encoding = header.substring(pos + 9, end); encoding = encoding.replace('\'', ' '); encoding = encoding.replace('\"', ' '); encoding = encoding.trim(); } } // Check XML-encoding if (encoding == null) { pos = header.indexOf("CHARSET="); if (pos != -1) { int end = endOf(header, pos + 10); if (end != -1) { encoding = header.substring(pos + 8, end); encoding = encoding.replace('\'', ' '); encoding = encoding.replace('\"', ' '); encoding = encoding.trim(); } } } // Convert file encoding to Java encoding if (encoding == null) { encoding = Charset.defaultCharset().name(); } else { if (encoding.equals("UTF8")) { encoding = StringUtils.UTF_8; } } log.debug("File encoding is '" + encoding + "'."); bytes = new byte[(int) raf.length()]; raf.seek(0); raf.readFully(bytes); content = StringUtils.decodeToString(bytes, encoding).trim(); } return content; }
From source file:ValidateLicenseHeaders.java
/** * Replace a legacy jboss header with the current default header * /*from w ww . j a v a 2 s . c om*/ * @param javaFile - * the java source file * @param endOfHeader - * the offset to the end of the legacy header * @throws IOException - * thrown on failure to replace the header */ static void replaceHeader(File javaFile, long endOfHeader) throws IOException { if (log.isLoggable(Level.FINE)) log.fine("Replacing legacy jboss header in: " + javaFile); RandomAccessFile raf = new RandomAccessFile(javaFile, "rw"); File bakFile = new File(javaFile.getAbsolutePath() + ".bak"); FileOutputStream fos = new FileOutputStream(bakFile); fos.write(DEFAULT_HEADER.getBytes()); FileChannel fc = raf.getChannel(); long count = raf.length() - endOfHeader; fc.transferTo(endOfHeader, count, fos.getChannel()); fc.close(); fos.close(); raf.close(); if (javaFile.delete() == false) log.severe("Failed to delete java file: " + javaFile); if (bakFile.renameTo(javaFile) == false) throw new SyncFailedException("Failed to replace: " + javaFile); }
From source file:com.polyvi.xface.util.XFileUtils.java
/** * ?//from w w w. j av a 2 s. com * * @param filePath * ? * @param size * size? * @return */ public static long truncateFile(String fileName, long size) throws FileNotFoundException, IOException { RandomAccessFile raf = new RandomAccessFile(fileName, "rw"); if (raf.length() >= size) { FileChannel channel = raf.getChannel(); channel.truncate(size); return size; } return raf.length(); }
From source file:azkaban.common.utils.Utils.java
/** * Read in content of a file and get the last *lineCount* lines. It is * equivalent to *tail* command/*www. ja va 2 s. c o m*/ * * @param filename * @param lineCount * @param chunkSize * @return */ public static Vector<String> tail(String filename, int lineCount, int chunkSize) { try { // read in content of the file RandomAccessFile file = new RandomAccessFile(filename, "r"); // destination vector Vector<String> lastNLines = new Vector<String>(); // current position long currPos = file.length() - 1; long startPos; byte[] byteArray = new byte[chunkSize]; // read in content of the file in reverse order while (true) { // read in from *fromPos* startPos = currPos - chunkSize; if (startPos <= 0) { // toward the beginning of the file file.seek(0); file.read(byteArray, 0, (int) currPos); // only read in // curPos bytes parseLinesFromLast(byteArray, 0, (int) currPos, lineCount, lastNLines); break; } else { file.seek(startPos); if (byteArray == null) byteArray = new byte[chunkSize]; file.readFully(byteArray); if (parseLinesFromLast(byteArray, lineCount, lastNLines)) { break; // we got the last *lineCount* lines } // move the current position currPos = startPos; // + lastLine.getBytes().length; } } // there might be lineCount + 1 lines and the first line (now it is the last line) // might not be complete for (int index = lineCount; index < lastNLines.size(); index++) lastNLines.removeElementAt(index); // reverse the order of elements in lastNLines Collections.reverse(lastNLines); return lastNLines; } catch (Exception e) { return null; } }
From source file:com.owncloud.android.utils.EncryptionUtils.java
/** * @param file file do crypt * @param encryptionKeyBytes key, either from metadata or {@link EncryptionUtils#generateKey()} * @param iv initialization vector, either from metadata or {@link EncryptionUtils#randomBytes(int)} * @return encryptedFile with encryptedBytes and authenticationTag *///from ww w . j a v a 2 s . c o m @RequiresApi(api = Build.VERSION_CODES.KITKAT) public static EncryptedFile encryptFile(File file, byte[] encryptionKeyBytes, byte[] iv) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, IOException { Cipher cipher = Cipher.getInstance(AES_CIPHER); Key key = new SecretKeySpec(encryptionKeyBytes, AES); GCMParameterSpec spec = new GCMParameterSpec(128, iv); cipher.init(Cipher.ENCRYPT_MODE, key, spec); RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r"); byte[] fileBytes = new byte[(int) randomAccessFile.length()]; randomAccessFile.readFully(fileBytes); byte[] cryptedBytes = cipher.doFinal(fileBytes); String authenticationTag = encodeBytesToBase64String( Arrays.copyOfRange(cryptedBytes, cryptedBytes.length - (128 / 8), cryptedBytes.length)); return new EncryptedFile(cryptedBytes, authenticationTag); }
From source file:com.owncloud.android.utils.EncryptionUtils.java
/** * @param file encrypted file * @param encryptionKeyBytes key from metadata * @param iv initialization vector from metadata * @param authenticationTag authenticationTag from metadata * @return decrypted byte[]/*from w ww. j ava 2s . c om*/ */ @RequiresApi(api = Build.VERSION_CODES.KITKAT) public static byte[] decryptFile(File file, byte[] encryptionKeyBytes, byte[] iv, byte[] authenticationTag) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, IOException { Cipher cipher = Cipher.getInstance(AES_CIPHER); Key key = new SecretKeySpec(encryptionKeyBytes, AES); GCMParameterSpec spec = new GCMParameterSpec(128, iv); cipher.init(Cipher.DECRYPT_MODE, key, spec); RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r"); byte[] fileBytes = new byte[(int) randomAccessFile.length()]; randomAccessFile.readFully(fileBytes); // check authentication tag byte[] extractedAuthenticationTag = Arrays.copyOfRange(fileBytes, fileBytes.length - (128 / 8), fileBytes.length); if (!Arrays.equals(extractedAuthenticationTag, authenticationTag)) { throw new SecurityException("Tag not correct"); } return cipher.doFinal(fileBytes); }
From source file:com.hdsfed.cometapi.HCPClient.java
/** * Copy the given byte range of the given input to the given output. * @param input The input to copy the given range to the given output for. * @param output The output to copy the given range from the given input for. * @param start Start of the byte range. * @param length Length of the byte range. * @throws IOException If something fails at I/O level. *//*from w w w .jav a2s . c o m*/ public static void FileToOutputStream(RandomAccessFile input, OutputStream output, long start, long length) throws IOException { byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; int read; if (input.length() == length) { // Write full range. while ((read = input.read(buffer)) > 0) { output.write(buffer, 0, read); } } else { // Write partial range. input.seek(start); long toRead = length; while ((read = input.read(buffer)) > 0) { if ((toRead -= read) > 0) { output.write(buffer, 0, read); } else { output.write(buffer, 0, (int) toRead + read); break; } } } }
From source file:net.naijatek.myalumni.util.utilities.FileUtil.java
public static String[] getLastLines(final File file, final int linesToReturn, final String logType) throws IOException, FileNotFoundException { final int AVERAGE_CHARS_PER_LINE = 250; final int BYTES_PER_CHAR = 2; RandomAccessFile randomAccessFile = null; StringBuffer buffer = new StringBuffer(linesToReturn * AVERAGE_CHARS_PER_LINE); int lineTotal = 0; try {// w ww .j a v a2 s. c om randomAccessFile = new RandomAccessFile(file, "r"); long byteTotal = randomAccessFile.length(); long byteEstimateToRead = linesToReturn * AVERAGE_CHARS_PER_LINE * BYTES_PER_CHAR; long offset = byteTotal - byteEstimateToRead; if (offset < 0) { offset = 0; } randomAccessFile.seek(offset); //log.debug("SKIP IS ::" + offset); String line = null; String lineUTF8 = null; while ((line = randomAccessFile.readLine()) != null) { lineUTF8 = new String(line.getBytes("ISO8859_1"), "UTF-8"); lineTotal++; buffer.append(lineUTF8).append("\n"); } } finally { if (randomAccessFile != null) { try { randomAccessFile.close(); } catch (IOException ex) { } } } //String[] resultLines = new String[linesToReturn]; ArrayList<String> resultLines = new ArrayList<String>(); BufferedReader in = null; try { in = new BufferedReader(new StringReader(buffer.toString())); int start = lineTotal /* + 2 */ - linesToReturn; // Ex : 55 - 10 = 45 ~ offset if (start < 0) { start = 0; // not start line } for (int i = 0; i < start; i++) { in.readLine(); // loop until the offset. Ex: loop 0, 1 ~~ 2 lines } int i = 0; String line = null; while ((line = in.readLine()) != null) { if (logType.equalsIgnoreCase("ALL")) { //resultLines[i] = line; resultLines.add(line); i++; } else if (line.indexOf(logType) > -1) { //resultLines[i] = line; resultLines.add(line); i++; } } } catch (IOException ie) { logger.error("Error" + ie); throw ie; } finally { if (in != null) { try { in.close(); } catch (IOException ex) { } } } String[] resultLines1 = new String[resultLines.size()]; String tmp = new String(); for (int i = 0; i < resultLines.size(); i++) { tmp = (String) resultLines.get(i); resultLines1[i] = tmp; } return resultLines1; }