List of usage examples for java.io RandomAccessFile length
public native long length() throws IOException;
From source file:org.xdi.util.FileUtil.java
/** * Writes data in a file on specified position * // w w w . j a v a 2s . c o m * @param filePath * @param position * @param data * @return */ public boolean writeToFile(String filePath, long position, String data) { try { File f = new File(filePath); RandomAccessFile raf; raf = new RandomAccessFile(f, "rw"); raf.seek(position); StringBuilder dataAfterPostion = new StringBuilder(data); while (raf.getFilePointer() < raf.length()) { String line = raf.readLine(); dataAfterPostion.append(line); } raf.seek(position); raf.writeUTF(dataAfterPostion.toString()); raf.close(); return true; } catch (FileNotFoundException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } }
From source file:org.openengsb.connector.promreport.internal.ProcessFileStore.java
private long findLastProcess(RandomAccessFile raf) throws IOException { final String proc = "</Process>"; final byte[] bproc = proc.getBytes(); final int len = proc.length(); for (long i = raf.length() - "</Process></WorkflowLog>".length(); i >= 0; i--) { byte[] buf = new byte[len]; raf.seek(i);// w w w . java 2 s.c om raf.readFully(buf, 0, len); int b; for (b = 0; b < len; b++) { if (buf[b] != bproc[b]) { break; } } if (b == len) { return i; } } return -1; }
From source file:com.l2jfree.gameserver.cache.CrestCache.java
public synchronized void reload() { FileFilter filter = new BmpFilter(); File dir = new File(Config.DATAPACK_ROOT, "data/crests/"); File[] files = dir.listFiles(filter); if (files == null) files = new File[0]; byte[] content; _loadedFiles = 0;// ww w. j a va 2 s . c om _bytesBuffLen = 0; _cachePledge.clear(); _cachePledgeLarge.clear(); _cacheAlly.clear(); for (File file : files) { RandomAccessFile f = null; try { f = new RandomAccessFile(file, "r"); content = new byte[(int) f.length()]; f.readFully(content); if (file.getName().startsWith("Crest_Large_")) { _cachePledgeLarge.put( Integer.valueOf(file.getName().substring(12, file.getName().length() - 4)), content); } else if (file.getName().startsWith("Crest_")) { _cachePledge.put(Integer.valueOf(file.getName().substring(6, file.getName().length() - 4)), content); } else if (file.getName().startsWith("AllyCrest_")) { _cacheAlly.put(Integer.valueOf(file.getName().substring(10, file.getName().length() - 4)), content); } _loadedFiles++; _bytesBuffLen += content.length; } catch (Exception e) { _log.warn("Problem with loading crest bmp file: " + file, e); } finally { try { if (f != null) f.close(); } catch (Exception e) { e.printStackTrace(); } } } _log.info(this); }
From source file:com.wondersgroup.cloud.deployment.file.FileServerHandler.java
@Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { HttpRequest request = (HttpRequest) e.getMessage(); if (request.getMethod() != GET) { sendError(ctx, METHOD_NOT_ALLOWED); return;//w w w. j a v a 2s. c o m } String srcPath = request.getHeader("srcPath"); String ipList = request.getHeader("ipList"); // ??app test: D:\cloud-deploy\DSC01575.JPG final String path = srcPath;// sanitizeUri(request.getUri()); "D:\\cloud-deploy\\AppTest.war";// if (path == null) { sendError(ctx, FORBIDDEN); return; } File file = new File(path); if (file.isHidden() || !file.exists()) { sendError(ctx, NOT_FOUND); return; } if (!file.isFile()) { sendError(ctx, FORBIDDEN); return; } RandomAccessFile raf; try { raf = new RandomAccessFile(file, "r"); } catch (FileNotFoundException fnfe) { sendError(ctx, NOT_FOUND); return; } long fileLength = raf.length(); HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); setContentLength(response, fileLength); response.setHeader("Content-disposition", "attachment;filename=" + file.getName()); Channel ch = e.getChannel(); // Write the initial line and the header. ch.write(response); // Write the content. ChannelFuture writeFuture; if (ch.getPipeline().get(SslHandler.class) != null) { // Cannot use zero-copy with HTTPS. writeFuture = ch.write(new ChunkedFile(raf, 0, fileLength, 8192)); } else { // No encryption - use zero-copy. final FileRegion region = new DefaultFileRegion(raf.getChannel(), 0, fileLength); writeFuture = ch.write(region); writeFuture.addListener(new ChannelFutureProgressListener() { public void operationComplete(ChannelFuture future) { region.releaseExternalResources(); } public void operationProgressed(ChannelFuture future, long amount, long current, long total) { System.out.printf("%s: %d / %d (+%d)%n", path, current, total, amount); } }); } // Decide whether to close the connection or not. if (!isKeepAlive(request)) { // Close the connection when the whole content is written out. writeFuture.addListener(ChannelFutureListener.CLOSE); } }
From source file:ro.ieugen.fileserver.http.HttpStaticFileServerHandler.java
private HttpResponse fileDownloadResponse(File file, RandomAccessFile raf) throws IOException { HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); long fileLength = raf.length(); setContentLength(response, fileLength); setContentTypeHeader(response, file); setDateAndCacheHeaders(response, file); return response; }
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();/*w w w . j a va 2 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:org.apache.tajo.HttpFileServerHandler.java
@Override public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { if (request.getMethod() != HttpMethod.GET) { sendError(ctx, HttpResponseStatus.METHOD_NOT_ALLOWED); return;// w w w . j a v a 2 s. c o m } final String path = sanitizeUri(request.getUri()); if (path == null) { sendError(ctx, HttpResponseStatus.FORBIDDEN); return; } File file = new File(path); if (file.isHidden() || !file.exists()) { sendError(ctx, HttpResponseStatus.NOT_FOUND); return; } if (!file.isFile()) { sendError(ctx, HttpResponseStatus.FORBIDDEN); return; } RandomAccessFile raf; try { raf = new RandomAccessFile(file, "r"); } catch (FileNotFoundException fnfe) { sendError(ctx, HttpResponseStatus.NOT_FOUND); return; } long fileLength = raf.length(); HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); HttpHeaders.setContentLength(response, fileLength); setContentTypeHeader(response); // Write the initial line and the header. ctx.write(response); // Write the content. ChannelFuture writeFuture; ChannelFuture lastContentFuture; if (ctx.pipeline().get(SslHandler.class) != null) { // Cannot use zero-copy with HTTPS. lastContentFuture = ctx.writeAndFlush(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)), ctx.newProgressivePromise()); } else { // No encryption - use zero-copy. final FileRegion region = new DefaultFileRegion(raf.getChannel(), 0, fileLength); writeFuture = ctx.write(region, ctx.newProgressivePromise()); lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); writeFuture.addListener(new ChannelProgressiveFutureListener() { @Override public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) throws Exception { LOG.trace(String.format("%s: %d / %d", path, progress, total)); } @Override public void operationComplete(ChannelProgressiveFuture future) throws Exception { LOG.trace(future.channel() + " Transfer complete."); } }); } // Decide whether to close the connection or not. if (!HttpHeaders.isKeepAlive(request)) { // Close the connection when the whole content is written out. lastContentFuture.addListener(ChannelFutureListener.CLOSE); } }
From source file:org.jraf.irondad.handler.pixgame.PixGameHandler.java
public String getRandomWord(HandlerContext handlerContext) throws IOException { RandomAccessFile file = new RandomAccessFile( ((PixGameHandlerConfig) handlerContext.getHandlerConfig()).getDictPath(), "r"); file.seek((long) (Math.random() * file.length())); // Eat the characters of the current line to go to beginning of the next line file.readLine();/*from w ww . ja va2 s .co m*/ // Now read and return the line return file.readLine(); }
From source file:hydrograph.ui.perspective.dialog.PreStartActivity.java
private boolean updateINIFile(String javaHome) { logger.debug("Updating JAVA_HOME in ini file ::" + javaHome); javaHome = "-vm\n" + javaHome + "\n"; RandomAccessFile file = null; boolean isUpdated = false; try {/* ww w.ja v a2 s . c om*/ file = new RandomAccessFile(new File(HYDROGRAPH_INI), "rw"); byte[] text = new byte[(int) file.length()]; file.readFully(text); file.seek(0); file.writeBytes(javaHome); file.write(text); isUpdated = true; } catch (IOException ioException) { logger.error("IOException occurred while updating " + HYDROGRAPH_INI + " file", ioException); } finally { try { if (file != null) { file.close(); } } catch (IOException ioException) { logger.error("IOException occurred while updating " + HYDROGRAPH_INI + " file", ioException); } } return isUpdated; }
From source file:at.tuwien.minimee.util.TopParser.java
/** * The process ID is in the last line of the file and looks like follows: * monitored_pid= 6738 /*from w w w . j a va2 s .com*/ * * @param input * @return * @throws Exception */ private Integer findPid() throws Exception { Integer pid = new Integer(0); // we open the file RandomAccessFile f = new RandomAccessFile(file, "r"); try { long size = f.length(); f.seek(size - 2); // we search the file reverse for '=' byte[] b = new byte[1]; for (long i = size - 2; i >= 0; i--) { f.seek(i); f.read(b); if (b[0] == '=') { break; } } String line = f.readLine().trim(); pid = new Integer(line); } finally { // this is important, RandomAccessFile doesn't close the file handle by default! // if close isn't called, you'll get very soon 'too many open files' f.close(); } return pid; }