Java Code Examples for java.nio.channels.FileChannel

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project ambrose, under directory /common/src/main/java/com/twitter/ambrose/util/.

Source file: JSONUtil.java

  33 
vote

public static String readFile(String path) throws IOException {
  FileInputStream stream=new FileInputStream(new File(path));
  try {
    FileChannel fc=stream.getChannel();
    MappedByteBuffer bb=fc.map(FileChannel.MapMode.READ_ONLY,0,fc.size());
    return Charset.defaultCharset().decode(bb).toString();
  }
  finally {
    stream.close();
  }
}
 

Example 2

From project Android-FFXIEQ, under directory /ffxieq/src/com/github/kanata3249/ffxieq/android/db/.

Source file: FFXIDatabase.java

  32 
vote

void copyDatabaseFromSD(String sd_path) throws IOException {
  File outDir=new File(DB_PATH);
  outDir.mkdir();
  FileChannel channelSource=new FileInputStream(sd_path + DB_NAME).getChannel();
  FileChannel channelTarget=new FileOutputStream(DB_PATH + DB_NAME).getChannel();
  channelSource.transferTo(0,channelSource.size(),channelTarget);
  channelSource.close();
  channelTarget.close();
  File from=new File(sd_path + DB_NAME);
  File to=new File(DB_PATH + DB_NAME);
  to.setLastModified(from.lastModified());
}
 

Example 3

From project android_external_guava, under directory /src/com/google/common/io/.

Source file: Files.java

  32 
vote

private static MappedByteBuffer map(RandomAccessFile raf,MapMode mode,long size) throws IOException {
  FileChannel channel=raf.getChannel();
  boolean threw=true;
  try {
    MappedByteBuffer mbb=channel.map(mode,0,size);
    threw=false;
    return mbb;
  }
  finally {
    Closeables.close(channel,threw);
  }
}
 

Example 4

From project autopsy, under directory /RecentActivity/src/org/sleuthkit/autopsy/recentactivity/.

Source file: Util.java

  32 
vote

public static String readFile(String path) throws IOException {
  FileInputStream stream=new FileInputStream(new File(path));
  try {
    FileChannel fc=stream.getChannel();
    MappedByteBuffer bb=fc.map(FileChannel.MapMode.READ_ONLY,0,fc.size());
    return Charset.defaultCharset().decode(bb).toString();
  }
  finally {
    stream.close();
  }
}
 

Example 5

From project bigger-tests, under directory /kernel/src/test/java/org/neo4j/kernel/impl/nioneo/store/.

Source file: TestUpgradeStore.java

  32 
vote

private void setOlderNeoStoreVersion(String path) throws IOException {
  String oldVersion="NeoStore v0.9.6";
  FileChannel channel=new RandomAccessFile(new File(path,NeoStore.DEFAULT_NAME),"rw").getChannel();
  channel.position(channel.size() - UTF8.encode(oldVersion).length);
  ByteBuffer buffer=ByteBuffer.wrap(UTF8.encode(oldVersion));
  channel.write(buffer);
  channel.close();
}
 

Example 6

From project bitcask-java, under directory /src/main/java/com/trifork/bitcask/.

Source file: BitCaskLock.java

  32 
vote

private void write_data(ByteString bytes) throws IOException {
  FileChannel ch=file.getChannel();
  if (is_write_lock) {
    ch.truncate(0);
    ch.write(bytes.asReadOnlyByteBuffer(),0);
    return;
  }
  throw new IOException("file not writable");
}
 

Example 7

From project Book-Catalogue, under directory /src/com/eleybourn/bookcatalogue/.

Source file: BookEditFields.java

  32 
vote

private void copyFile(File src,File dst) throws IOException {
  FileChannel inChannel=new FileInputStream(src).getChannel();
  FileChannel outChannel=new FileOutputStream(dst).getChannel();
  try {
    inChannel.transferTo(0,inChannel.size(),outChannel);
  }
  finally {
    if (inChannel != null)     inChannel.close();
    if (outChannel != null)     outChannel.close();
  }
}
 

Example 8

From project Carolina-Digital-Repository, under directory /metadata/src/main/java/edu/unc/lib/dl/util/.

Source file: FileUtils.java

  32 
vote

public static void copyFile(File in,File out) throws IOException {
  FileChannel inChannel=new FileInputStream(in).getChannel();
  FileChannel outChannel=new FileOutputStream(out).getChannel();
  try {
    inChannel.transferTo(0,inChannel.size(),outChannel);
  }
 catch (  IOException e) {
    throw e;
  }
 finally {
    if (inChannel != null)     inChannel.close();
    if (outChannel != null)     outChannel.close();
  }
}
 

Example 9

From project CIShell, under directory /templates/org.cishell.templates/src/org/cishell/templates/dataset/.

Source file: DatasetFactory.java

  32 
vote

private File copyFile(File dir,String path) throws IOException {
  URL entry=bContext.getBundle().getEntry(path);
  path=path.replace('/',File.separatorChar);
  File outFile=File.createTempFile(getName(path) + "-",".tmp",dir);
  FileOutputStream outStream=new FileOutputStream(outFile);
  ReadableByteChannel in=Channels.newChannel(entry.openStream());
  FileChannel out=outStream.getChannel();
  out.transferFrom(in,0,Integer.MAX_VALUE);
  in.close();
  out.close();
  return outFile;
}
 

Example 10

From project crawler4j, under directory /src/main/java/edu/uci/ics/crawler4j/util/.

Source file: IO.java

  32 
vote

public static void writeBytesToFile(byte[] bytes,String destination){
  try {
    FileChannel fc=new FileOutputStream(destination).getChannel();
    fc.write(ByteBuffer.wrap(bytes));
    fc.close();
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
}
 

Example 11

From project droidparts, under directory /extra/src/org/droidparts/util/io/.

Source file: IOUtils.java

  32 
vote

public static void copy(File fileFrom,File fileTo) throws IOException {
  FileChannel src=null;
  FileChannel dst=null;
  try {
    src=new FileInputStream(fileFrom).getChannel();
    dst=new FileOutputStream(fileTo).getChannel();
    dst.transferFrom(src,0,src.size());
  }
  finally {
    silentlyClose(src,dst);
  }
}
 

Example 12

From project eucalyptus, under directory /clc/modules/storage-controller/src/edu/ucsb/eucalyptus/storage/.

Source file: LVM2Manager.java

  32 
vote

public void dupFile(String oldFileName,String newFileName){
  try {
    FileChannel out=new FileOutputStream(new File(newFileName)).getChannel();
    FileChannel in=new FileInputStream(new File(oldFileName)).getChannel();
    in.transferTo(0,in.size(),out);
    in.close();
    out.close();
  }
 catch (  Exception ex) {
    ex.printStackTrace();
  }
}
 

Example 13

From project flapjack, under directory /flapjack/src/main/java/flapjack/io/.

Source file: FileUtilImpl.java

  32 
vote

public ByteBuffer map(ScatteringByteChannel channel,long offset,long length){
  if (channel instanceof FileChannel) {
    FileChannel fileChannel=(FileChannel)channel;
    try {
      return fileChannel.map(FileChannel.MapMode.READ_ONLY,offset,length);
    }
 catch (    IOException e) {
      throw new RuntimeException(e);
    }
  }
  throw new IllegalArgumentException("Channel is NOT a FileChannel it is a " + channel.getClass().getName());
}
 

Example 14

From project friendica-for-android, under directory /mw-android-friendica-01/src/de/wikilab/android/friendica01/.

Source file: Max.java

  32 
vote

public static String readFile(String path) throws IOException {
  FileInputStream stream=new FileInputStream(new File(path));
  try {
    FileChannel fc=stream.getChannel();
    MappedByteBuffer bb=fc.map(FileChannel.MapMode.READ_ONLY,0,fc.size());
    return Charset.defaultCharset().decode(bb).toString();
  }
  finally {
    stream.close();
  }
}
 

Example 15

From project GnucashMobile, under directory /GnucashMobile/src/org/gnucash/android/ui/accounts/.

Source file: ExportDialogFragment.java

  32 
vote

/** 
 * Copies a file from <code>src</code> to <code>dst</code>
 * @param src Absolute path to the source file
 * @param dst Absolute path to the destination file 
 * @throws IOException if the file could not be copied
 */
public static void copyFile(File src,File dst) throws IOException {
  FileChannel inChannel=new FileInputStream(src).getChannel();
  FileChannel outChannel=new FileOutputStream(dst).getChannel();
  try {
    inChannel.transferTo(0,inChannel.size(),outChannel);
  }
  finally {
    if (inChannel != null)     inChannel.close();
    if (outChannel != null)     outChannel.close();
  }
}
 

Example 16

From project httpcore, under directory /httpcore-nio/src/main/java/org/apache/http/nio/entity/.

Source file: NFileEntity.java

  32 
vote

/** 
 * {@inheritDoc}
 * @since 4.2
 */
public void close() throws IOException {
  FileChannel local=fileChannel;
  fileChannel=null;
  if (local != null) {
    local.close();
  }
}
 

Example 17

From project i18n, under directory /src/main/java/com/ovea/i18n/util/.

Source file: Resource.java

  32 
vote

static byte[] readBytes(File file) throws IOException {
  FileChannel channel=null;
  ByteArrayOutputStream baos=new ByteArrayOutputStream();
  transfer(file,Channels.newChannel(baos));
  return baos.toByteArray();
}
 

Example 18

From project indextank-engine, under directory /src/main/java/com/flaptor/indextank/storage/.

Source file: LogRoot.java

  32 
vote

public boolean unlockComponent(String name){
  FileChannel channel=components.remove(name);
  if (channel == null) {
    return false;
  }
  Execute.close(channel);
  return true;
}
 

Example 19

From project james-mime4j, under directory /examples/src/main/java/org/apache/james/mime4j/samples/mbox/.

Source file: IterateOverMbox.java

  32 
vote

private static void saveMessageToFile(int count,CharBuffer buf) throws IOException {
  FileOutputStream fout=new FileOutputStream(new File("target/messages/msg-" + count));
  FileChannel fileChannel=fout.getChannel();
  ByteBuffer buf2=ENCODER.encode(buf);
  fileChannel.write(buf2);
  fileChannel.close();
  fout.close();
}
 

Example 20

From project Japid, under directory /tests/cn/bran/japid/compiler/.

Source file: CompilerTests.java

  32 
vote

private static String readFile(String path) throws IOException {
  FileInputStream stream=new FileInputStream(new File(path));
  try {
    FileChannel fc=stream.getChannel();
    MappedByteBuffer bb=fc.map(FileChannel.MapMode.READ_ONLY,0,fc.size());
    return Charset.forName("UTF-8").decode(bb).toString();
  }
  finally {
    stream.close();
  }
}
 

Example 21

From project jCAE, under directory /amibe/src/org/jcae/mesh/xmldata/.

Source file: Groups.java

  32 
vote

private void copyFile(File src,File dst) throws IOException {
  FileChannel sourceChannel=new FileInputStream(src).getChannel();
  FileChannel destinationChannel=new FileOutputStream(dst).getChannel();
  destinationChannel.transferFrom(sourceChannel,0,sourceChannel.size());
  sourceChannel.close();
  destinationChannel.close();
}
 

Example 22

From project jcarder, under directory /src/com/enea/jcarder/common/contexts/.

Source file: ContextFileReader.java

  32 
vote

public ContextFileReader(Logger logger,File file) throws IOException {
  mLogger=logger;
  RandomAccessFile raFile=new RandomAccessFile(file,"r");
  final String path=file.getCanonicalPath();
  mLogger.info("Opening for reading: " + path);
  FileChannel roChannel=raFile.getChannel();
  if (roChannel.size() > Integer.MAX_VALUE) {
    throw new IOException("File too large: " + path);
  }
  mBuffer=roChannel.map(FileChannel.MapMode.READ_ONLY,0,(int)roChannel.size());
  roChannel.close();
  raFile.close();
  validateHeader(path);
}
 

Example 23

From project jcr-openofficeplugin, under directory /src/main/java/org/exoplatform/applications/ooplugin/utils/.

Source file: WebDavUtils.java

  32 
vote

public static byte[] getBytes(File inFile) throws Exception {
  FileInputStream fis=new FileInputStream(inFile);
  FileChannel fc=fis.getChannel();
  byte[] data=new byte[(int)fc.size()];
  ByteBuffer bb=ByteBuffer.wrap(data);
  fc.read(bb);
  return data;
}
 

Example 24

From project jena-tdb, under directory /src/main/java/com/hp/hpl/jena/tdb/base/file/.

Source file: ChannelManager.java

  32 
vote

private static FileChannel openref$(String filename,String mode){
  if (!filename.endsWith(".jrnl")) {
    return open$(filename,mode);
  }
  FileChannel chan=name2channel.get(filename);
  if (chan != null) {
    throw new FileException("Already open: " + filename);
  }
  chan=open$(filename,mode);
  name2channel.put(filename,chan);
  channel2name.put(chan,filename);
  return chan;
}
 

Example 25

From project agile, under directory /agile-storage/src/main/java/org/headsupdev/agile/storage/.

Source file: HibernateStorage.java

  31 
vote

private void copyFiles(File src,File dest) throws IOException {
  if (src.isDirectory()) {
    dest.mkdirs();
    String[] files=src.list();
    for (    String fileName : files) {
      File src1=new File(src,fileName);
      File dest1=new File(dest,fileName);
      copyFiles(src1,dest1);
    }
  }
 else {
    FileChannel sourceChannel=new FileInputStream(src).getChannel();
    FileChannel targetChannel=new FileOutputStream(dest).getChannel();
    sourceChannel.transferTo(0,sourceChannel.size(),targetChannel);
    sourceChannel.close();
    targetChannel.close();
  }
}
 

Example 26

From project akubra, under directory /akubra-fs/src/main/java/org/akubraproject/fs/.

Source file: FSBlob.java

  31 
vote

private static void nioCopy(File source,File dest) throws IOException {
  FileInputStream f_in=null;
  FileOutputStream f_out=null;
  log.debug("Performing force copy-and-delete of source '" + source + "' to '"+ dest+ "'");
  try {
    f_in=new FileInputStream(source);
    try {
      f_out=new FileOutputStream(dest);
      FileChannel in=f_in.getChannel();
      FileChannel out=f_out.getChannel();
      in.transferTo(0,source.length(),out);
    }
  finally {
      IOUtils.closeQuietly(f_out);
    }
  }
  finally {
    IOUtils.closeQuietly(f_in);
  }
  if (!dest.exists())   throw new IOException("Failed to copy file to new location: " + dest);
}
 

Example 27

From project AmDroid, under directory /httpclientandroidlib/src/ch/boye/httpclientandroidlib/impl/client/cache/.

Source file: IOUtils.java

  31 
vote

static void copyFile(final File in,final File out) throws IOException {
  RandomAccessFile f1=new RandomAccessFile(in,"r");
  RandomAccessFile f2=new RandomAccessFile(out,"rw");
  try {
    FileChannel c1=f1.getChannel();
    FileChannel c2=f2.getChannel();
    try {
      c1.transferTo(0,f1.length(),c2);
      c1.close();
      c2.close();
    }
 catch (    IOException ex) {
      closeSilently(c1);
      closeSilently(c2);
      throw ex;
    }
    f1.close();
    f2.close();
  }
 catch (  IOException ex) {
    closeSilently(f1);
    closeSilently(f2);
    throw ex;
  }
}
 

Example 28

From project and-bible, under directory /AndBible/src/net/bible/service/common/.

Source file: FileManager.java

  31 
vote

public static boolean copyFile(String filename,File fromDir,File toDir){
  log.debug("Copying:" + filename);
  boolean ok=false;
  try {
    toDir.mkdir();
    File fromFile=new File(fromDir,filename);
    File targetFile=new File(toDir,filename);
    if (fromFile.exists()) {
      long fromFileSize=fromFile.length();
      log.debug("Source file length:" + fromFileSize);
      if (fromFileSize > CommonUtils.getFreeSpace(toDir.getPath())) {
        ok=false;
      }
 else {
        FileChannel src=new FileInputStream(fromFile).getChannel();
        FileChannel dst=new FileOutputStream(targetFile).getChannel();
        try {
          dst.transferFrom(src,0,src.size());
          ok=true;
        }
  finally {
          src.close();
          dst.close();
        }
      }
    }
 else {
      ok=false;
    }
  }
 catch (  Exception e) {
    log.error("Error moving file to sd card",e);
  }
  return ok;
}
 

Example 29

From project androidquery, under directory /src/com/androidquery/.

Source file: AbstractAQuery.java

  31 
vote

/** 
 * Create a temporary file on EXTERNAL storage (sdcard) that holds the cached content of the url. Returns null if url is not cached, or the system cannot create such file (sdcard is absent, such as in emulator). The returned file is accessable to all apps, therefore it is ideal for sharing content (such as photo) via the intent mechanism. <br> <br> Example Usage: <pre> Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("image/jpeg"); intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file)); startActivityForResult(Intent.createChooser(intent, "Share via:"), 0); </pre> <br> The temp file will be deleted when AQUtility.cleanCacheAsync is invoked, or the file can be explicitly deleted after use.
 * @param url The url of the desired cached content.
 * @param filename The desired file name, which might be used by other apps to describe the content, such as an email attachment.
 * @return temp file
 */
public File makeSharedFile(String url,String filename){
  File file=null;
  try {
    File cached=getCachedFile(url);
    if (cached != null) {
      File temp=AQUtility.getTempDir();
      if (temp != null) {
        file=new File(temp,filename);
        file.createNewFile();
        FileChannel ic=new FileInputStream(cached).getChannel();
        FileChannel oc=new FileOutputStream(file).getChannel();
        try {
          ic.transferTo(0,ic.size(),oc);
        }
  finally {
          if (ic != null)           ic.close();
          if (oc != null)           oc.close();
        }
      }
    }
  }
 catch (  Exception e) {
    AQUtility.debug(e);
  }
  return file;
}
 

Example 30

From project ant4eclipse, under directory /org.ant4eclipse.lib.core/src/org/ant4eclipse/lib/core/util/.

Source file: Utilities.java

  31 
vote

/** 
 * Copies one file to another location.
 * @param source The original File which has to be copied. Not <code>null</code>.
 * @param to The destination File which has to be written. Not <code>null</code>.
 */
public static final void copy(File source,File to){
  Assure.isFile("source",source);
  Assure.notNull("to",to);
  FileInputStream instream=null;
  FileOutputStream outstream=null;
  FileChannel readchannel=null;
  FileChannel writechannel=null;
  try {
    instream=new FileInputStream(source);
    outstream=new FileOutputStream(to);
    readchannel=instream.getChannel();
    writechannel=outstream.getChannel();
    readchannel.transferTo(0,readchannel.size(),writechannel);
  }
 catch (  IOException ex) {
    throw new Ant4EclipseException(ex,CoreExceptionCode.COPY_FAILURE,source.getAbsolutePath(),to.getAbsolutePath());
  }
 finally {
    close(readchannel);
    close(writechannel);
    close(instream);
    close(outstream);
  }
}
 

Example 31

From project apb, under directory /modules/apb-base/src/apb/utils/.

Source file: FileUtils.java

  31 
vote

public static void copyFile(@NotNull File from,@NotNull File to,boolean append) throws IOException {
  FileInputStream in=null;
  FileOutputStream out=null;
  try {
    out=createOutputStream(to,append);
    in=new FileInputStream(from);
    FileChannel readChannel=in.getChannel();
    FileChannel writeChannel=out.getChannel();
    long size=readChannel.size();
    for (long position=0; position < size; ) {
      position+=readChannel.transferTo(position,MB,writeChannel);
    }
    if (from.length() != to.length()) {
      throw new IOException("Failed to copy full contents from " + from + " to "+ to);
    }
  }
  finally {
    StreamUtils.close(in);
    StreamUtils.close(out);
  }
}
 

Example 32

From project aranea, under directory /core/src/main/java/no/dusken/aranea/util/.

Source file: ImageUtils.java

  31 
vote

/** 
 * common This creates an image object from a pdf file, and saves the image to the database The image created is default 640x480, use setMaxHeight, setMaxWidth to change
 * @param pdfFile is the pdf file to use (first page is used)
 * @return the image object created
 * @throws IOException if anything goes wrong
 */
public Image makeThumbnail(File pdfFile) throws IOException {
  if (pdfFile == null || !pdfFile.exists() || !pdfFile.isFile()) {
    throw new IOException("No file");
  }
  log.debug("making thumb for pdf: {}",pdfFile.getAbsolutePath());
  RandomAccessFile raf=new RandomAccessFile(pdfFile,"r");
  FileChannel channel=raf.getChannel();
  ByteBuffer buf=channel.map(FileChannel.MapMode.READ_ONLY,0,channel.size());
  PDFFile pdffile=new PDFFile(buf);
  PDFPage page=pdffile.getPage(0);
  Rectangle rect=new Rectangle(0,0,(int)page.getBBox().getWidth(),(int)page.getBBox().getHeight());
  java.awt.Image img=page.getImage(rect.width,rect.height,rect,null,true,true);
  img=img.getScaledInstance(-1,PDF_HEIGHT,BufferedImage.SCALE_SMOOTH);
  BufferedImage buffScaledPDFImage;
{
    buffScaledPDFImage=new BufferedImage(img.getWidth(null),img.getHeight(null),BufferedImage.TYPE_INT_RGB);
    Graphics g=buffScaledPDFImage.createGraphics();
    g.drawImage(img,0,0,null);
    g.dispose();
  }
  File tmpImageFile=new File(imageDirectory + "/tmp/" + pdfFile.getName()+ ".png");
  tmpImageFile.getParentFile().mkdirs();
  if (tmpImageFile.exists()) {
    tmpImageFile.delete();
  }
  ImageIO.write(buffScaledPDFImage,"png",tmpImageFile);
  Image i=storeImageService.createImage(tmpImageFile);
  i.setDescription("Thumb for pdf: " + pdfFile.getName());
  i.setExternalSource("From PDF");
  return i;
}
 

Example 33

From project archive-commons, under directory /archive-commons/src/test/java/org/archive/format/gzip/zipnum/.

Source file: ZipNumWriterTest.java

  31 
vote

public void testAddRecord() throws IOException {
  Charset UTF8=Charset.forName("UTF-8");
  File main=File.createTempFile("test-znw",".main");
  File summ=File.createTempFile("test-znw",".summ");
  main.deleteOnExit();
  summ.deleteOnExit();
  System.out.format("Summ: %s\n",summ.getAbsolutePath());
  int limit=10;
  ZipNumWriter znw=new ZipNumWriter(new FileOutputStream(main,false),new FileOutputStream(summ,false),limit);
  for (int i=0; i < 1000; i++) {
    znw.addRecord(String.format("%06d\n",i).getBytes(UTF8));
  }
  znw.close();
  InputStreamReader isr=new InputStreamReader(new FileInputStream(summ),UTF8);
  BufferedReader br=new BufferedReader(isr);
  String line=null;
  int count=0;
  while (true) {
    line=br.readLine();
    if (line == null) {
      break;
    }
    String parts[]=line.split("\t");
    FileChannel fc=new RandomAccessFile(main,"r").getChannel();
    long offset=Long.parseLong(parts[0]);
    int len=Integer.parseInt(parts[1]);
    byte[] gz=new byte[len];
    ByteBuffer bb=ByteBuffer.wrap(gz);
    int amt=fc.read(bb,offset);
    assertEquals(amt,len);
    ByteArrayInputStream bais=new ByteArrayInputStream(gz);
    GZIPMemberSeries gzms=new GZIPMemberSeries(new SimpleStream(bais));
    GZIPSeriesMember m=gzms.getNextMember();
    m.skipMember();
    gzms.close();
    count++;
  }
  assertEquals(count,100);
  br.close();
}
 

Example 34

From project avro, under directory /lang/java/avro/src/test/java/org/apache/avro/reflect/.

Source file: ByteBufferTest.java

  31 
vote

private void writeOneXAsAvro(Schema schema,ByteArrayOutputStream bout) throws IOException, FileNotFoundException {
  DatumWriter<X> datumWriter=new ReflectDatumWriter<X>(schema);
  DataFileWriter<X> writer=new DataFileWriter<X>(datumWriter);
  writer.create(schema,bout);
  X x=new X();
  x.name="xxx";
  FileInputStream fis=new FileInputStream(content);
  try {
    FileChannel channel=fis.getChannel();
    try {
      long contentLength=content.length();
      ByteBuffer buffer=channel.map(FileChannel.MapMode.READ_ONLY,0,contentLength);
      x.content=buffer;
      writer.append(x);
    }
  finally {
      channel.close();
    }
  }
  finally {
    fis.close();
  }
  writer.flush();
  writer.close();
}
 

Example 35

From project Cafe, under directory /webapp/src/org/openqa/selenium/io/.

Source file: FileHandler.java

  31 
vote

private static void copyFile(File from,File to,Filter onlyCopy) throws IOException {
  if (!onlyCopy.isRequired(from)) {
    return;
  }
  FileChannel out=null;
  FileChannel in=null;
  try {
    in=new FileInputStream(from).getChannel();
    out=new FileOutputStream(to).getChannel();
    final long length=in.size();
    final long copied=in.transferTo(0,in.size(),out);
    if (copied != length) {
      throw new IOException("Could not transfer all bytes.");
    }
  }
  finally {
    Closeables.closeQuietly(out);
    Closeables.closeQuietly(in);
  }
}
 

Example 36

From project Catroid-maven-playground, under directory /src/main/java/at/tugraz/ist/catroid/io/.

Source file: StorageHandler.java

  31 
vote

private File copyFile(File destinationFile,File sourceFile,File directory) throws IOException {
  FileChannel inputChannel=new FileInputStream(sourceFile).getChannel();
  FileChannel outputChannel=new FileOutputStream(destinationFile).getChannel();
  String checksumSource=Utils.md5Checksum(sourceFile);
  FileChecksumContainer fileChecksumContainer=ProjectManager.getInstance().fileChecksumContainer;
  try {
    inputChannel.transferTo(0,inputChannel.size(),outputChannel);
    fileChecksumContainer.addChecksum(checksumSource,destinationFile.getAbsolutePath());
    return destinationFile;
  }
 catch (  IOException e) {
    e.printStackTrace();
    return null;
  }
 finally {
    if (inputChannel != null) {
      inputChannel.close();
    }
    if (outputChannel != null) {
      outputChannel.close();
    }
  }
}
 

Example 37

From project CBCJVM, under directory /eclipse/src/cbcdownloader/.

Source file: DummyDownloader.java

  31 
vote

private void copyFile(File from,File to) throws IOException {
  if (from.isFile()) {
    to.delete();
    to.createNewFile();
    FileChannel in=new FileInputStream(from).getChannel();
    FileChannel out=new FileOutputStream(to).getChannel();
    in.transferTo(0,in.size(),out);
    in.close();
    out.close();
  }
 else {
    to.mkdir();
    for (    File k : from.listFiles()) {
      copyFile(k,new File(to.getPath() + File.separator + k.getName()));
    }
  }
}
 

Example 38

From project ceres, under directory /ceres-binio/src/test/java/com/bc/ceres/binio/util/.

Source file: FileChannelTest.java

  31 
vote

public void testIt() throws IOException {
  raf=new RandomAccessFile(file,"rw");
  FileChannel channel=raf.getChannel();
  assertTrue(channel.isOpen());
  byte[] array=new byte[16];
  ByteBuffer buffer=ByteBuffer.wrap(array);
  buffer.putLong(123456789);
  buffer.putLong(987654321);
  buffer.rewind();
  int n=channel.write(buffer);
  channel.force(true);
  assertEquals(16,n);
  assertEquals(16,channel.size());
  channel.close();
  raf=new RandomAccessFile(file,"r");
  channel=raf.getChannel();
  assertEquals(16,channel.size());
  array=new byte[16];
  buffer=ByteBuffer.wrap(array);
  channel.read(buffer);
  buffer.rewind();
  assertEquals(123456789,buffer.getLong());
  assertEquals(987654321,buffer.getLong());
  channel.close();
}
 

Example 39

From project Codeable_Objects, under directory /SoftObjects/src/com/ui/.

Source file: FileImport.java

  31 
vote

public String readFile(String path) throws IOException {
  FileInputStream stream=new FileInputStream(new File(path));
  try {
    FileChannel fc=stream.getChannel();
    MappedByteBuffer bb=fc.map(FileChannel.MapMode.READ_ONLY,0,fc.size());
    try {
      System.out.println(Charset.defaultCharset().decode(bb).toString());
      this.getPoints(Charset.defaultCharset().decode(bb).toString());
    }
 catch (    Exception e) {
      e.printStackTrace();
    }
 finally {
      System.out.println("file import fail");
    }
    return Charset.defaultCharset().decode(bb).toString();
  }
  finally {
    stream.close();
  }
}
 

Example 40

From project commons-io, under directory /src/main/java/org/apache/commons/io/.

Source file: FileUtils.java

  31 
vote

/** 
 * Internal copy file method.
 * @param srcFile  the validated source file, must not be {@code null}
 * @param destFile  the validated destination file, must not be {@code null}
 * @param preserveFileDate  whether to preserve the file date
 * @throws IOException if an error occurs
 */
private static void doCopyFile(File srcFile,File destFile,boolean preserveFileDate) throws IOException {
  if (destFile.exists() && destFile.isDirectory()) {
    throw new IOException("Destination '" + destFile + "' exists but is a directory");
  }
  FileInputStream fis=null;
  FileOutputStream fos=null;
  FileChannel input=null;
  FileChannel output=null;
  try {
    fis=new FileInputStream(srcFile);
    fos=new FileOutputStream(destFile);
    input=fis.getChannel();
    output=fos.getChannel();
    long size=input.size();
    long pos=0;
    long count=0;
    while (pos < size) {
      count=size - pos > FILE_COPY_BUFFER_SIZE ? FILE_COPY_BUFFER_SIZE : size - pos;
      pos+=output.transferFrom(input,pos,count);
    }
  }
  finally {
    IOUtils.closeQuietly(output);
    IOUtils.closeQuietly(fos);
    IOUtils.closeQuietly(input);
    IOUtils.closeQuietly(fis);
  }
  if (srcFile.length() != destFile.length()) {
    throw new IOException("Failed to copy full contents from '" + srcFile + "' to '"+ destFile+ "'");
  }
  if (preserveFileDate) {
    destFile.setLastModified(srcFile.lastModified());
  }
}
 

Example 41

From project dawn-common, under directory /org.dawb.common.util/src/org/dawb/common/util/io/.

Source file: FileUtils.java

  31 
vote

/** 
 * @param source_file
 * @param destination_file
 * @throws IOException
 */
public final static void copyNio(final File source_file,final File destination_file) throws IOException {
  if (!source_file.exists()) {
    return;
  }
  final File parTo=destination_file.getParentFile();
  if (!parTo.exists()) {
    parTo.mkdirs();
  }
  if (!destination_file.exists()) {
    destination_file.createNewFile();
  }
  FileChannel srcChannel=null, dstChannel=null;
  try {
    srcChannel=new FileInputStream(source_file).getChannel();
    dstChannel=new FileOutputStream(destination_file).getChannel();
    dstChannel.transferFrom(srcChannel,0,srcChannel.size());
  }
  finally {
    if (srcChannel != null) {
      srcChannel.close();
    }
    if (dstChannel != null) {
      dstChannel.close();
    }
  }
}
 

Example 42

From project dawn-isenciaui, under directory /com.isencia.passerelle.workbench.model.ui/src/main/java/com/isencia/passerelle/workbench/model/ui/utils/.

Source file: FileUtils.java

  31 
vote

/** 
 * @param source_file
 * @param destination_file
 * @throws IOException
 */
public final static void copyNio(final File source_file,final File destination_file) throws IOException {
  if (!source_file.exists()) {
    return;
  }
  final File parTo=destination_file.getParentFile();
  if (!parTo.exists()) {
    parTo.mkdirs();
  }
  if (!destination_file.exists()) {
    destination_file.createNewFile();
  }
  FileChannel srcChannel=null, dstChannel=null;
  try {
    srcChannel=new FileInputStream(source_file).getChannel();
    dstChannel=new FileOutputStream(destination_file).getChannel();
    dstChannel.transferFrom(srcChannel,0,srcChannel.size());
  }
  finally {
    if (srcChannel != null) {
      srcChannel.close();
    }
    if (dstChannel != null) {
      dstChannel.close();
    }
  }
}
 

Example 43

From project dolphin, under directory /dolphinmaple/src/com/tan/util/.

Source file: ReadBook.java

  31 
vote

public final static String readBookByNio(final String p){
  FileInputStream fis=null;
  FileChannel fc=null;
  try {
    fis=new FileInputStream(p);
    fc=fis.getChannel();
    ByteBuffer buf=ByteBuffer.allocate((int)fc.size());
    fc.read(buf);
    buf.flip();
    String content=new String(buf.array(),"utf-8");
    if (content != null && !"".equals(content)) {
      return content;
    }
  }
 catch (  Exception e) {
  }
 finally {
    if (fc != null) {
      try {
        fc.close();
      }
 catch (      IOException e) {
      }
    }
  }
  return "";
}
 

Example 44

From project DTRules, under directory /compilerutil/src/main/java/com/dtrules/compiler/excel/util/.

Source file: Excel2XML.java

  31 
vote

/** 
 * Copy a file Throws a runtime exception if anything goes wrong. 
 */
public static void copyFile(String file1,String file2){
  FileChannel inChannel=null;
  FileChannel outChannel=null;
  try {
    inChannel=new FileInputStream(file1).getChannel();
    outChannel=new FileOutputStream(file2).getChannel();
    try {
      int blksize=(64 * 1024 * 1024) - 1024;
      long size=inChannel.size();
      long position=0;
      while (position < size) {
        position+=inChannel.transferTo(position,blksize,outChannel);
      }
      inChannel.close();
      outChannel.close();
    }
 catch (    IOException e) {
      throw new RuntimeException(e.getMessage());
    }
  }
 catch (  FileNotFoundException e) {
    throw new RuntimeException(e);
  }
}
 

Example 45

From project dungbeetle, under directory /src/edu/stanford/mobisocial/dungbeetle/util/.

Source file: Util.java

  31 
vote

public static void copyFile(FileInputStream fromFile,FileOutputStream toFile) throws IOException {
  FileChannel fromChannel=null;
  FileChannel toChannel=null;
  try {
    fromChannel=fromFile.getChannel();
    toChannel=toFile.getChannel();
    fromChannel.transferTo(0,fromChannel.size(),toChannel);
  }
  finally {
    try {
      if (fromChannel != null) {
        fromChannel.close();
      }
    }
  finally {
      if (toChannel != null) {
        toChannel.close();
      }
    }
  }
}
 

Example 46

From project EasySOA, under directory /easysoa-registry/easysoa-registry-api/easysoa-registry-api-frascati/src/main/java/org/easysoa/registry/frascati/.

Source file: FileUtils.java

  31 
vote

/** 
 * Copy a file in an other file
 * @param source The source file
 * @param target The target file
 * @throws Exception If a problem occurs
 */
public static final void copyTo(File source,File target) throws Exception {
  if (source == null || target == null) {
    throw new IllegalArgumentException("Source and target files must not be null");
  }
  log.debug("source file = " + source);
  log.debug("target file = " + target);
  FileChannel in=null;
  FileChannel out=null;
  try {
    in=new FileInputStream(source).getChannel();
    out=new FileOutputStream(target).getChannel();
    in.transferTo(0,in.size(),out);
  }
 catch (  Exception ex) {
    throw ex;
  }
 finally {
    if (in != null) {
      try {
        in.close();
      }
 catch (      IOException e) {
      }
    }
    if (out != null) {
      try {
        out.close();
      }
 catch (      IOException e) {
      }
    }
  }
}
 

Example 47

From project eclipse-integration-commons, under directory /org.springsource.ide.eclipse.commons.frameworks.core/src/org/springsource/ide/eclipse/commons/frameworks/core/legacyconversion/.

Source file: AbstractLegacyConverter.java

  31 
vote

public static void copyFile(File sourceFile,File destFile) throws IOException {
  if (!sourceFile.exists()) {
    return;
  }
  if (!destFile.exists()) {
    destFile.createNewFile();
  }
  FileChannel source=null;
  FileChannel destination=null;
  try {
    source=new FileInputStream(sourceFile).getChannel();
    destination=new FileOutputStream(destFile).getChannel();
    destination.transferFrom(source,0,source.size());
  }
  finally {
    if (source != null) {
      source.close();
    }
    if (destination != null) {
      destination.close();
    }
  }
}
 

Example 48

From project encfs-java, under directory /src/main/java/org/mrpdaemon/sec/encfs/.

Source file: EncFSLocalFileProvider.java

  31 
vote

/** 
 * Copy the file with the given path to another destination
 * @param srcFilePath Path to the file to copy
 * @param dstFilePath Path to the destination file
 * @return true if copy was successful, false otherwise
 * @throws IOException Destination file already exists, source file doesn't exist or misc. I/O error
 */
public boolean copy(String srcFilePath,String dstFilePath) throws IOException {
  File sourceFile=new File(rootPath.getAbsoluteFile(),srcFilePath);
  File destFile=new File(rootPath.getAbsoluteFile(),dstFilePath);
  if (!sourceFile.exists()) {
    throw new FileNotFoundException("Source file '" + srcFilePath + "' doesn't exist!");
  }
  if (!destFile.exists()) {
    destFile.createNewFile();
  }
  FileChannel source=null;
  FileChannel destination=null;
  try {
    source=new FileInputStream(sourceFile).getChannel();
    destination=new FileOutputStream(destFile).getChannel();
    destination.transferFrom(source,0,source.size());
  }
  finally {
    if (source != null) {
      source.close();
    }
    if (destination != null) {
      destination.close();
    }
  }
  return true;
}
 

Example 49

From project enterprise, under directory /backup/src/main/java/org/neo4j/backup/.

Source file: RebuildFromLogs.java

  31 
vote

private static long findLastTransactionId(File storeDir,String logFileName){
  long txId;
  try {
    FileChannel channel=new RandomAccessFile(new File(storeDir,logFileName),"r").getChannel();
    try {
      ByteBuffer buffer=ByteBuffer.allocateDirect(9 + Xid.MAXGTRIDSIZE + Xid.MAXBQUALSIZE * 10);
      txId=LogIoUtils.readLogHeader(buffer,channel,true)[1];
      XaCommandFactory cf=new CommandFactory();
      for (LogEntry entry; (entry=LogIoUtils.readEntry(buffer,channel,cf)) != null; ) {
        if (entry instanceof LogEntry.Commit) {
          txId=((LogEntry.Commit)entry).getTxId();
        }
      }
    }
  finally {
      if (channel != null)       channel.close();
    }
  }
 catch (  IOException e) {
    return -1;
  }
  return txId;
}
 

Example 50

From project fasthat, under directory /src/com/sun/tools/hat/internal/parser/.

Source file: MappedReadBuffer.java

  31 
vote

static ReadBuffer create(RandomAccessFile file) throws IOException {
  FileChannel ch=file.getChannel();
  long size=ch.size();
  if (canUseFileMap() && (size <= Integer.MAX_VALUE)) {
    MappedByteBuffer buf;
    try {
      buf=ch.map(FileChannel.MapMode.READ_ONLY,0,size);
      ch.close();
      return new MappedReadBuffer(buf);
    }
 catch (    IOException exp) {
      exp.printStackTrace();
      System.err.println("File mapping failed, will use direct read");
    }
  }
  return new FileReadBuffer(file);
}
 

Example 51

From project fire-samples, under directory /cache-demo/src/main/java/demo/vmware/util/.

Source file: PersistenceDirectoryGenerator.java

  31 
vote

private boolean lock(File directory){
  String name="node.lock";
  File lockfile=new File(directory,name);
  lockfile.deleteOnExit();
  try {
    RandomAccessFile rf=new RandomAccessFile(lockfile,"rw");
    FileChannel fc=rf.getChannel();
    System.err.println("Attempting to lock:" + lockfile);
    lock=fc.tryLock();
    System.err.println("Locked:" + lock);
    if (lock != null) {
      File f=new File(directory,"BACKUPdefault.if");
      boolean result=true;
      if (f.exists()) {
        result=f.delete();
      }
      f=new File(directory,"DRLK_IFdefault.lk");
      if (result && f.exists()) {
        result=f.delete();
      }
      return result;
    }
  }
 catch (  IOException x) {
  }
catch (  OverlappingFileLockException e) {
  }
  return false;
}
 

Example 52

From project Flume-Hive, under directory /src/javatest/com/cloudera/flume/handlers/text/.

Source file: TestFileNIO.java

  31 
vote

/** 
 * if sleep = 0 there there is no pause between writes.
 */
public CountDownLatch slowWrite(File f,final int sleep) throws IOException {
  final FileOutputStream fos=new FileOutputStream(f);
  final FileChannel out=fos.getChannel();
  final CountDownLatch done=new CountDownLatch(1);
  Thread t=new Thread(){
    public void run(){
      try {
        for (int i=0; i < 100; i++) {
          ByteBuffer buf=ByteBuffer.wrap(("test " + i + "\n").getBytes());
          out.write(buf);
          if (sleep > 0) {
            Clock.sleep(sleep);
          }
        }
        fos.close();
        done.countDown();
      }
 catch (      Exception e) {
        LOG.error("Exception when running thread",e);
      }
    }
  }
;
  t.start();
  return done;
}
 

Example 53

From project flume_1, under directory /flume-core/src/test/java/com/cloudera/flume/handlers/text/.

Source file: TestFileNIO.java

  31 
vote

/** 
 * if sleep = 0 there there is no pause between writes.
 */
public CountDownLatch slowWrite(File f,final int sleep) throws IOException {
  final FileOutputStream fos=new FileOutputStream(f);
  final FileChannel out=fos.getChannel();
  final CountDownLatch done=new CountDownLatch(1);
  Thread t=new Thread(){
    public void run(){
      try {
        for (int i=0; i < 100; i++) {
          ByteBuffer buf=ByteBuffer.wrap(("test " + i + "\n").getBytes());
          out.write(buf);
          if (sleep > 0) {
            Clock.sleep(sleep);
          }
        }
        fos.close();
        done.countDown();
      }
 catch (      Exception e) {
        LOG.error("Exception when running thread",e);
      }
    }
  }
;
  t.start();
  return done;
}
 

Example 54

From project gda-common, under directory /uk.ac.gda.common/src/uk/ac/gda/util/io/.

Source file: FileUtils.java

  31 
vote

/** 
 * @param source_file
 * @param destination_file
 * @throws IOException
 */
public final static void copyNio(final File source_file,final File destination_file) throws IOException {
  if (!source_file.exists()) {
    return;
  }
  final File parTo=destination_file.getParentFile();
  if (!parTo.exists()) {
    parTo.mkdirs();
  }
  if (!destination_file.exists()) {
    destination_file.createNewFile();
  }
  FileChannel srcChannel=null, dstChannel=null;
  try {
    srcChannel=new FileInputStream(source_file).getChannel();
    dstChannel=new FileOutputStream(destination_file).getChannel();
    dstChannel.transferFrom(srcChannel,0,srcChannel.size());
  }
  finally {
    if (srcChannel != null) {
      srcChannel.close();
    }
    if (dstChannel != null) {
      dstChannel.close();
    }
  }
}
 

Example 55

From project gecko, under directory /src/test/java/com/taobao/gecko/service/impl/.

Source file: TransferFileUnitTest.java

  31 
vote

@Test public void testTransferFile() throws Exception {
  final ServerConfig serverConfig=new ServerConfig();
  serverConfig.setWireFormatType(new NotifyWireFormatType());
  serverConfig.setPort(this.port++);
  final RemotingServer server=RemotingFactory.bind(serverConfig);
  final String url=server.getConnectURI().toString();
  final File file=File.createTempFile("remoting","test");
  file.delete();
  final FileChannel channel=new RandomAccessFile(file,"rw").getChannel();
  final ByteBuffer buff=ByteBuffer.allocate(7);
  buff.put("hello".getBytes());
  buff.flip();
  channel.write(buff);
  channel.force(true);
  server.registerProcessor(NotifyDummyRequestCommand.class,new RequestProcessor<NotifyDummyRequestCommand>(){
    public ThreadPoolExecutor getExecutor(){
      return null;
    }
    public void handleRequest(    final NotifyDummyRequestCommand request,    final Connection conn){
      conn.transferFrom(IoBuffer.wrap("head ".getBytes()),IoBuffer.wrap(" tail\r\n".getBytes()),channel,0,7);
    }
  }
);
  final Socket socket=new Socket();
  socket.connect(server.getInetSocketAddress());
  final DataOutputStream out=new DataOutputStream(socket.getOutputStream());
  out.writeByte(0x80);
  out.writeByte(0x13);
  out.writeShort(0);
  out.writeInt(0);
  out.writeInt(0);
  out.flush();
  final BufferedReader reader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
  final String line=reader.readLine();
  assertEquals("head hello tail",line);
  server.stop();
  socket.close();
  channel.close();
  file.delete();
}
 

Example 56

From project GenericKnimeNodes, under directory /com.genericworkflownodes.knime.base_plugin/src/org/ballproject/knime/base/util/.

Source file: Helper.java

  31 
vote

public static void copyFile(File in,File out) throws IOException {
  FileChannel inChannel=new FileInputStream(in).getChannel();
  FileChannel outChannel=new FileOutputStream(out).getChannel();
  try {
    inChannel.transferTo(0,inChannel.size(),outChannel);
  }
 catch (  IOException e) {
    throw e;
  }
 finally {
    if (inChannel != null) {
      inChannel.close();
    }
    if (outChannel != null) {
      outChannel.close();
    }
  }
}
 

Example 57

From project GSM-Signal-Tracking-, under directory /gpstracker/src/nl/sogeti/android/gpstracker/actions/utils/.

Source file: XmlCreator.java

  31 
vote

/** 
 * Copies media into the export directory and returns the relative path of the media
 * @param inputFilePath
 * @return file path relative to the export dir
 * @throws IOException
 */
protected String includeMediaFile(String inputFilePath) throws IOException {
  mNeedsBundling=true;
  File source=new File(inputFilePath);
  File target=new File(mExportDirectoryPath + "/" + source.getName());
  if (source.exists()) {
    FileChannel inChannel=new FileInputStream(source).getChannel();
    FileChannel outChannel=new FileOutputStream(target).getChannel();
    try {
      inChannel.transferTo(0,inChannel.size(),outChannel);
    }
 catch (    IOException e) {
      throw e;
    }
 finally {
      if (inChannel != null)       inChannel.close();
      if (outChannel != null)       outChannel.close();
    }
  }
 else {
    target.createNewFile();
  }
  if (mProgressListener != null) {
    mProgressListener.increaseProgress(100);
  }
  return target.getName();
}
 

Example 58

From project ha-jdbc, under directory /src/main/java/net/sf/hajdbc/sql/.

Source file: FileSupportImpl.java

  31 
vote

/** 
 * @see net.sf.hajdbc.sql.FileSupport#createFile(java.io.InputStream)
 */
@Override public File createFile(InputStream inputStream) throws E {
  try {
    File file=this.createTempFile();
    FileOutputStream output=new FileOutputStream(file);
    try {
      FileChannel fileChannel=output.getChannel();
      ReadableByteChannel inputChannel=Channels.newChannel(inputStream);
      ByteBuffer buffer=ByteBuffer.allocate(BUFFER_SIZE);
      while (inputChannel.read(buffer) > 0) {
        buffer.flip();
        fileChannel.write(buffer);
        buffer.compact();
      }
      return file;
    }
  finally {
      Resources.close(output);
    }
  }
 catch (  IOException e) {
    throw this.exceptionFactory.createException(e);
  }
}
 

Example 59

From project hank, under directory /src/java/com/rapleaf/hank/performance/.

Source file: RandomReadPerformance.java

  31 
vote

@Override public void run(){
  try {
    Random random=new Random();
    byte[] readBufferArray=new byte[randomReadBufferSize];
    ByteBuffer readBuffer=ByteBuffer.wrap(readBufferArray);
    HankTimer timer=timerAggregator.getTimer();
    for (int i=0; i < NUM_RANDOM_READS; ++i) {
      readBuffer.clear();
      FileChannel testChannel=testChannels[i % testChannels.length];
      long randomPosition=Math.abs(random.nextLong()) % (testChannel.size() - randomReadBufferSize);
      testChannel.position(randomPosition).read(readBuffer);
    }
    timerAggregator.add(timer,NUM_RANDOM_READS);
    for (    FileChannel testChannel : testChannels) {
      testChannel.close();
    }
  }
 catch (  Exception e) {
    LOG.error("Failed to perform random reads",e);
  }
}
 

Example 60

From project http-testing-harness, under directory /server-provider/src/main/java/org/sonatype/tests/http/server/jetty/util/.

Source file: FileUtil.java

  31 
vote

public static long copy(File src,File target) throws IOException {
  RandomAccessFile in=null;
  RandomAccessFile out=null;
  FileChannel inChannel=null;
  FileChannel outChannel=null;
  try {
    in=new RandomAccessFile(src,"r");
    target.getParentFile().mkdirs();
    out=new RandomAccessFile(target,"rw");
    out.setLength(0);
    long size=in.length();
    long chunk=(64 * 1024 * 1024) - (32 * 1024);
    inChannel=in.getChannel();
    outChannel=out.getChannel();
    int total=0;
    do {
      total+=inChannel.transferTo(total,chunk,outChannel);
    }
 while (total < size);
    return total;
  }
  finally {
    close(inChannel);
    close(outChannel);
    close(in);
    close(out);
  }
}
 

Example 61

From project httpClient, under directory /httpclient-cache/src/main/java/org/apache/http/impl/client/cache/.

Source file: IOUtils.java

  31 
vote

static void copyFile(final File in,final File out) throws IOException {
  RandomAccessFile f1=new RandomAccessFile(in,"r");
  RandomAccessFile f2=new RandomAccessFile(out,"rw");
  try {
    FileChannel c1=f1.getChannel();
    FileChannel c2=f2.getChannel();
    try {
      c1.transferTo(0,f1.length(),c2);
      c1.close();
      c2.close();
    }
 catch (    IOException ex) {
      closeSilently(c1);
      closeSilently(c2);
      throw ex;
    }
    f1.close();
    f2.close();
  }
 catch (  IOException ex) {
    closeSilently(f1);
    closeSilently(f2);
    throw ex;
  }
}
 

Example 62

From project incubator-cordova-android, under directory /framework/src/org/apache/cordova/.

Source file: FileUtils.java

  31 
vote

/** 
 * Copy a file
 * @param srcFile file to be copied
 * @param destFile destination to be copied to
 * @return a FileEntry object
 * @throws IOException
 * @throws InvalidModificationException
 * @throws JSONException
 */
private JSONObject copyFile(File srcFile,File destFile) throws IOException, InvalidModificationException, JSONException {
  if (destFile.exists() && destFile.isDirectory()) {
    throw new InvalidModificationException("Can't rename a file to a directory");
  }
  FileInputStream istream=new FileInputStream(srcFile);
  FileOutputStream ostream=new FileOutputStream(destFile);
  FileChannel input=istream.getChannel();
  FileChannel output=ostream.getChannel();
  try {
    input.transferTo(0,input.size(),output);
  }
  finally {
    istream.close();
    ostream.close();
    input.close();
    output.close();
  }
  return getEntry(destFile);
}
 

Example 63

From project iPage, under directory /src/main/java/com/github/zhongl/io/.

Source file: IterableFile.java

  31 
vote

public <T>Iterator<T> toIterator(final Function<ByteBuffer,T> function){
  return new AbstractIterator<T>(){
    private ByteBuffer byteBuffer=(ByteBuffer)ByteBuffer.allocateDirect(BUFFER_SIZE).position(BUFFER_SIZE);
    private long position=0;
    @Override protected synchronized T computeNext(){
      while (true) {
        try {
          int last=byteBuffer.position();
          ByteBuffer duplicate=byteBuffer.duplicate();
          T object=function.apply(duplicate);
          byteBuffer.position(duplicate.position());
          position+=byteBuffer.position() - last;
          return object;
        }
 catch (        RuntimeException e) {
          if (isNotOutOfBound(e))           throw e;
          try {
            FileChannel channel=stream.getChannel();
            if (position >= channel.size()) {
              DirectByteBufferCleaner.clean(byteBuffer);
              Closeables.closeQuietly(stream);
              return endOfData();
            }
            byteBuffer.clear();
            FileChannels.read(channel,position,byteBuffer);
          }
 catch (          IOException ex) {
            throw new IllegalStateException(ex);
          }
        }
      }
    }
  }
;
}
 

Example 64

From project james, under directory /protocols-imap4/src/main/java/org/apache/james/imapserver/netty/.

Source file: ChannelImapResponseWriter.java

  31 
vote

/** 
 * @see org.apache.james.imap.encode.ImapResponseWriter#write(org.apache.james.imap.message.response.Literal)
 */
public void write(Literal literal) throws IOException {
  if (channel.isConnected()) {
    InputStream in=literal.getInputStream();
    if (in instanceof FileInputStream && channel.getFactory() instanceof NioServerSocketChannelFactory) {
      FileChannel fc=((FileInputStream)in).getChannel();
      ChannelPipeline cp=channel.getPipeline();
      if (zeroCopy && cp.get(SslHandler.class) == null && cp.get(ZlibEncoder.class) == null) {
        channel.write(new DefaultFileRegion(fc,fc.position(),literal.size()));
      }
 else {
        channel.write(new ChunkedNioFile(fc,8192));
      }
    }
 else {
      channel.write(new ChunkedStream(literal.getInputStream()));
    }
  }
}
 

Example 65

From project JDBM3, under directory /src/main/java/org/apache/jdbm/.

Source file: StorageDiskMapped.java

  31 
vote

private FileChannel getChannel(long pageNumber) throws IOException {
  int fileNumber=(int)(Math.abs(pageNumber) / PAGES_PER_FILE);
  List<FileChannel> c=pageNumber >= 0 ? channels : channelsTranslation;
  for (int i=c.size(); i <= fileNumber; i++) {
    c.add(null);
  }
  FileChannel ret=c.get(fileNumber);
  if (ret == null) {
    String name=makeFileName(fileName,pageNumber,fileNumber);
    ret=new RandomAccessFile(name,"rw").getChannel();
    c.set(fileNumber,ret);
    buffers.put(ret,ret.map(FileChannel.MapMode.READ_WRITE,0,ret.size()));
  }
  return ret;
}
 

Example 66

From project jentrata-msh, under directory /Clients/Corvus.WSClient/src/main/java/hk/hku/cecid/corvus/http/.

Source file: EnvelopQuerySender.java

  31 
vote

/** 
 * [@EVENT] This method is invoked when received the reply HTTP  response from the server. <br/><br/> It saves the response body stream and then available to get through by  {@link #getEnvelopStream()}
 */
protected void onResponse() throws Exception {
  HttpMethod post=this.getExecutedMethod();
  InputStream ins=post.getResponseBodyAsStream();
  if (ins.available() < THRESHOLD) {
    byte[] envelop=IOHandler.readBytes(ins);
    this.envelopStream=new ByteArrayInputStream(envelop);
  }
 else {
    File envelopTmp=new File(BASE_PATH + this.hashCode());
    envelopTmp.deleteOnExit();
    FileChannel fChannel=new FileInputStream(envelopTmp).getChannel();
    fChannel.transferFrom(Channels.newChannel(ins),0,ins.available());
    fChannel.close();
    this.envelopStream=new BufferedInputStream(new FileInputStream(envelopTmp));
  }
}
 

Example 67

From project JGit, under directory /org.spearce.jgit/src/org/spearce/jgit/lib/.

Source file: GitIndex.java

  31 
vote

/** 
 * Read the cache file into memory.
 * @throws IOException
 */
public void read() throws IOException {
  changed=false;
  statDirty=false;
  if (!cacheFile.exists()) {
    header=null;
    entries.clear();
    lastCacheTime=0;
    return;
  }
  cache=new RandomAccessFile(cacheFile,"r");
  try {
    FileChannel channel=cache.getChannel();
    ByteBuffer buffer=ByteBuffer.allocateDirect((int)cacheFile.length());
    buffer.order(ByteOrder.BIG_ENDIAN);
    int j=channel.read(buffer);
    if (j != buffer.capacity())     throw new IOException("Could not read index in one go, only " + j + " out of "+ buffer.capacity()+ " read");
    buffer.flip();
    header=new Header(buffer);
    entries.clear();
    for (int i=0; i < header.entries; ++i) {
      Entry entry=new Entry(buffer);
      entries.put(entry.name,entry);
    }
    lastCacheTime=cacheFile.lastModified();
  }
  finally {
    cache.close();
  }
}
 

Example 68

From project aether-core, under directory /aether-impl/src/main/java/org/eclipse/aether/internal/impl/.

Source file: TrackingFileManager.java

  29 
vote

private FileLock lock(FileChannel channel,long size,boolean shared) throws IOException {
  FileLock lock=null;
  for (int attempts=8; attempts >= 0; attempts--) {
    try {
      lock=channel.lock(0,size,shared);
      break;
    }
 catch (    OverlappingFileLockException e) {
      if (attempts <= 0) {
        throw (IOException)new IOException().initCause(e);
      }
      try {
        Thread.sleep(50);
      }
 catch (      InterruptedException e1) {
        Thread.currentThread().interrupt();
      }
    }
  }
  if (lock == null) {
    throw new IOException("Could not lock file");
  }
  return lock;
}
 

Example 69

From project android-aac-enc, under directory /src/com/coremedia/iso/boxes/mdat/.

Source file: MediaDataBox.java

  29 
vote

public void parse(ReadableByteChannel readableByteChannel,ByteBuffer header,long contentSize,BoxParser boxParser) throws IOException {
  this.header=header;
  if (readableByteChannel instanceof FileChannel && contentSize > 1024 * 1024) {
    content=((FileChannel)readableByteChannel).map(FileChannel.MapMode.READ_ONLY,((FileChannel)readableByteChannel).position(),contentSize);
    ((FileChannel)readableByteChannel).position(((FileChannel)readableByteChannel).position() + contentSize);
  }
 else {
    content=ChannelHelper.readFully(readableByteChannel,l2i(contentSize));
  }
}
 

Example 70

From project CommitCoin, under directory /src/com/google/bitcoin/store/.

Source file: BoundedOverheadBlockStore.java

  29 
vote

public static void write(FileChannel channel,StoredBlock block) throws IOException {
  ByteBuffer buf=ByteBuffer.allocate(Record.SIZE);
  buf.putInt(block.getHeight());
  byte[] chainWorkBytes=block.getChainWork().toByteArray();
  checkState(chainWorkBytes.length <= CHAIN_WORK_BYTES,"Ran out of space to store chain work!");
  if (chainWorkBytes.length < CHAIN_WORK_BYTES) {
    buf.put(EMPTY_BYTES,0,CHAIN_WORK_BYTES - chainWorkBytes.length);
  }
  buf.put(chainWorkBytes);
  buf.put(block.getHeader().bitcoinSerialize());
  buf.position(0);
  channel.position(channel.size());
  if (channel.write(buf) < Record.SIZE)   throw new IOException("Failed to write record!");
  channel.position(channel.size() - Record.SIZE);
}
 

Example 71

From project erjang, under directory /src/main/java/erjang/driver/efile/.

Source file: EFile.java

  29 
vote

/** 
 * @param command
 * @param driver 
 */
public EFile(EString command,Driver driver){
  super(driver);
  this.fd=(FileChannel)null;
  this.flags=0;
  this.invoke=null;
  this.cq=new LinkedList<FileAsync>();
  this.timer_state=TimerState.IDLE;
  this.read_binp=(ByteBuffer)null;
  this.write_delay=0L;
  this.write_bufsize=0;
  this.q_mtx=driver_pdl_create();
  this.write_buffered=0;
}
 

Example 72

From project heritrix3, under directory /commons/src/main/java/org/archive/io/.

Source file: GenericReplayCharSequence.java

  29 
vote

private void updateMemoryMappedBuffer(){
  long charLength=(long)this.length() - (long)prefixBuffer.limit();
  long mapSize=Math.min((charLength * bytesPerChar) - mapByteOffset,MAP_MAX_BYTES);
  logger.fine("updateMemoryMappedBuffer: mapOffset=" + NumberFormat.getInstance().format(mapByteOffset) + " mapSize="+ NumberFormat.getInstance().format(mapSize));
  try {
    mappedBuffer=backingFileChannel.map(FileChannel.MapMode.READ_ONLY,mapByteOffset,mapSize).asReadOnlyBuffer().asCharBuffer();
  }
 catch (  IOException e) {
    DevUtils.logger.log(Level.SEVERE," backingFileChannel.map() mapByteOffset=" + mapByteOffset + " mapSize="+ mapSize+ "\n"+ "decodedFile="+ decodedFile+ " length="+ length+ "\n"+ DevUtils.extraInfo(),e);
    throw new RuntimeException(e);
  }
}
 

Example 73

From project jafka, under directory /src/main/java/com/sohu/jafka/message/.

Source file: FileMessageSet.java

  29 
vote

public FileMessageSet(FileChannel channel,long offset,long limit,boolean mutable,AtomicBoolean needRecover) throws IOException {
  super();
  this.channel=channel;
  this.offset=offset;
  this.mutable=mutable;
  this.needRecover=needRecover;
  if (mutable) {
    if (limit < Long.MAX_VALUE || offset > 0)     throw new IllegalArgumentException("Attempt to open a mutable message set with a view or offset, which is not allowed.");
    if (needRecover.get()) {
      long startMs=System.currentTimeMillis();
      long truncated=recover();
      logger.info("Recovery succeeded in " + (System.currentTimeMillis() - startMs) / 1000 + " seconds. " + truncated + " bytes truncated.");
    }
 else {
      setSize.set(channel.size());
      setHighWaterMark.set(getSizeInBytes());
      channel.position(channel.size());
    }
  }
 else {
    setSize.set(Math.min(channel.size(),limit) - offset);
    setHighWaterMark.set(getSizeInBytes());
  }
}
 

Example 74

From project james-mailbox, under directory /store/src/main/java/org/apache/james/mailbox/store/streaming/.

Source file: LimitingFileInputStream.java

  29 
vote

@Override public FileChannel position(long newPosition) throws IOException {
  if (newPosition <= limit) {
    channel.position(newPosition);
  }
  return LimitingFileChannel.this;
}
 

Example 75

From project Java-Chronicle, under directory /src/main/java/vanilla/java/chronicle/impl/.

Source file: IndexedChronicle.java

  29 
vote

protected ByteBuffer acquireIndexBuffer(long startPosition){
  if (startPosition >= MAX_VIRTUAL_ADDRESS)   throw new IllegalStateException("ByteOrder is incorrect.");
  int indexBufferId=(int)(startPosition >> indexBitSize);
  while (indexBuffers.size() <= indexBufferId)   indexBuffers.add(null);
  ByteBuffer buffer=indexBuffers.get(indexBufferId);
  if (buffer != null)   return buffer;
  try {
    MappedByteBuffer mbb=indexChannel.map(FileChannel.MapMode.READ_WRITE,startPosition & ~indexLowMask,1 << indexBitSize);
    mbb.order(byteOrder);
    indexBuffers.set(indexBufferId,mbb);
    return mbb;
  }
 catch (  IOException e) {
    throw new IllegalStateException(e);
  }
}