Java Code Examples for java.io.FileOutputStream.getChannel()

The following are Jave code examples for showing how to use getChannel() of the java.io.FileOutputStream class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: VideoCompressor   File: MP4Builder.java   View Source Code Vote up 6 votes
public MP4Builder createMovie(Mp4Movie mp4Movie) throws Exception {
    currentMp4Movie = mp4Movie;

    fos = new FileOutputStream(mp4Movie.getCacheFile());
    fc = fos.getChannel();

    FileTypeBox fileTypeBox = createFileTypeBox();
    fileTypeBox.getBox(fc);
    dataOffset += fileTypeBox.getSize();
    writedSinceLastMdat += dataOffset;

    mdat = new InterleaveChunkMdat();

    sizeBuffer = ByteBuffer.allocateDirect(4);

    return this;
}
 
Example 2
Project: labtablet   File: FileMgr.java   View Source Code Vote up 6 votes
/**
 * Moves a file to another location
 * @param src source
 * @param dst destination
 * @throws IOException
 */
public static void moveFile(File src, File dst) throws IOException {
    if (!dst.exists()) {
        Log.i("New File", "" + dst.createNewFile());
    }

    FileInputStream inStream = new FileInputStream(src);
    FileOutputStream outStream = new FileOutputStream(dst);
    FileChannel inChannel = inStream.getChannel();
    FileChannel outChannel = outStream.getChannel();
    inChannel.transferTo(0, inChannel.size(), outChannel);
    if (!src.delete()){
        Log.e("moveFile", "Failed to delete file");
    }

    inStream.close();
    outStream.close();
}
 
Example 3
Project: RetroMusicPlayer   File: TaggerUtils.java   View Source Code Vote up 6 votes
static void copyFile(File sourceFile, FileOutputStream outputStream) throws IOException {

        FileChannel source = null;
        FileChannel destination = null;

        try {
            source = new FileInputStream(sourceFile).getChannel();
            destination = outputStream.getChannel();
            destination.transferFrom(source, 0, source.size());
        } finally {
            if (source != null) {
                source.close();
            }
            if (destination != null) {
                destination.close();
            }
        }
    }
 
Example 4
Project: Remindy   File: FileUtil.java   View Source Code Vote up 6 votes
/**
 * Creates the specified <code>toFile</code> as a byte for byte copy of the
 * <code>fromFile</code>. If <code>toFile</code> already exists, then it
 * will be replaced with a copy of <code>fromFile</code>. The name and path
 * of <code>toFile</code> will be that of <code>toFile</code>.<br/>
 * <br/>
 * <i> Note: <code>fromFile</code> and <code>toFile</code> will be closed by
 * this function.</i>
 *
 * @param fromFile
 *            - FileInputStream for the file to copy from.
 * @param toFile
 *            - FileInputStream for the file to copy to.
 */
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 5
Project: PlusGram   File: MP4Builder.java   View Source Code Vote up 6 votes
public MP4Builder createMovie(Mp4Movie mp4Movie) throws Exception {
    currentMp4Movie = mp4Movie;

    fos = new FileOutputStream(mp4Movie.getCacheFile());
    fc = fos.getChannel();

    FileTypeBox fileTypeBox = createFileTypeBox();
    fileTypeBox.getBox(fc);
    dataOffset += fileTypeBox.getSize();
    writedSinceLastMdat += dataOffset;

    mdat = new InterleaveChunkMdat();

    sizeBuffer = ByteBuffer.allocateDirect(4);

    return this;
}
 
Example 6
Project: Rey-MusicPlayer   File: FileUtils.java   View Source Code Vote up 6 votes
public static void copyFile(File sourceFile, FileOutputStream outputStream) throws IOException {

        FileChannel source = null;
        FileChannel destination = null;

        try {
            source = new FileInputStream(sourceFile).getChannel();
            destination = outputStream.getChannel();
            destination.transferFrom(source, 0, source.size());
        } finally {
            if (source != null) {
                source.close();
            }
            if (destination != null) {
                destination.close();
            }
        }
    }
 
Example 7
Project: Android-Practice   File: MainActivity.java   View Source Code Vote up 5 votes
@Override
public boolean onTouch(View v, MotionEvent ev) {

    if (ev.getAction() == MotionEvent.ACTION_UP)
    {
        mAdapter.add("" + ev.getAxisValue(0) + ", " + ev.getAxisValue(1));

        try {
            FileOutputStream fos = openFileOutput ("MousePos.txt", Context.MODE_APPEND);
            FileChannel outChannel = fos.getChannel();

            float[] pos = new float[2];
            pos[0] = ev.getAxisValue(0);
            pos[1] = ev.getAxisValue(1);

            ByteBuffer buff = ByteBuffer.allocate(4*2);
            buff.clear();
            buff.asFloatBuffer().put(pos);

            outChannel.write(buff);
            outChannel.close();
            fos.close();

            FileInputStream fis = openFileInput ("MousePos.txt");
            int a = fis.available();
            int b = 0;

        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
    }

    return false;
}
 
Example 8
Project: GitHub   File: ProcessLock.java   View Source Code Vote up 5 votes
private static ProcessLock tryLockInternal(final String lockName, final String hash, final boolean writeMode) {
    synchronized (LOCK_MAP) {

        ConcurrentHashMap<Integer, ProcessLock> locks = LOCK_MAP.get(lockName);
        if (locks != null && !locks.isEmpty()) {
            Iterator<Map.Entry<Integer, ProcessLock>> itr = locks.entrySet().iterator();
            while (itr.hasNext()) {
                Map.Entry<Integer, ProcessLock> entry = itr.next();
                ProcessLock value = entry.getValue();
                if (value != null) {
                    if (!value.isValid()) {
                        itr.remove();
                    } else if (writeMode) {
                        return null;
                    } else if (value.mWriteMode) {
                        return null;
                    }
                } else {
                    itr.remove();
                }
            }
        }

        FileChannel channel = null;
        Closeable stream = null;
        try {
            File file = new File(
                    x.app().getDir(LOCK_FILE_DIR, Context.MODE_PRIVATE),
                    hash);
            if (file.exists() || file.createNewFile()) {

                if (writeMode) {
                    FileOutputStream out = new FileOutputStream(file, false);
                    channel = out.getChannel();
                    stream = out;
                } else {
                    FileInputStream in = new FileInputStream(file);
                    channel = in.getChannel();
                    stream = in;
                }
                if (channel != null) {
                    FileLock fileLock = channel.tryLock(0L, Long.MAX_VALUE, !writeMode);
                    if (isValid(fileLock)) {
                        ProcessLock result = new ProcessLock(lockName, file, fileLock, stream, writeMode);
                        LOCK_MAP.put(lockName, fileLock.hashCode(), result);
                        return result;
                    } else {
                        release(lockName, fileLock, file, stream);
                    }
                } else {
                    throw new IOException("can not get file channel:" + file.getAbsolutePath());
                }
            }
        } catch (Throwable ignored) {
            LogUtil.d("tryLock: " + lockName + ", " + ignored.getMessage());
            IOUtil.closeQuietly(stream);
            IOUtil.closeQuietly(channel);
        }
    }

    return null;
}
 
Example 9
Project: incubator-netbeans   File: DataConsistentFileOutputStream.java   View Source Code Vote up 5 votes
static void truncateFileToConsistentSize(FileOutputStream fos, long size) {
    try {
        FileChannel fch = fos.getChannel();
        fch.truncate(size);
        fch.force(true);
    } catch (IOException ex) {
        Logger.getLogger(DataConsistentFileOutputStream.class.getName()).log(
                Level.INFO,
                "Not able to truncate file to the data consistent size of "+size+" bytes.",
                ex);
    }
}
 
Example 10
Project: hadoop   File: TestOfflineEditsViewer.java   View Source Code Vote up 5 votes
@Test
public void testRecoveryMode() throws IOException {
  // edits generated by nnHelper (MiniDFSCluster), should have all op codes
  // binary, XML, reparsed binary
  String edits = nnHelper.generateEdits();
  FileOutputStream os = new FileOutputStream(edits, true);
  // Corrupt the file by truncating the end
  FileChannel editsFile = os.getChannel();
  editsFile.truncate(editsFile.size() - 5);

  String editsParsedXml = folder.newFile("editsRecoveredParsed.xml")
      .getAbsolutePath();
  String editsReparsed = folder.newFile("editsRecoveredReparsed")
      .getAbsolutePath();
  String editsParsedXml2 = folder.newFile("editsRecoveredParsed2.xml")
      .getAbsolutePath();

  // Can't read the corrupted file without recovery mode
  assertEquals(-1, runOev(edits, editsParsedXml, "xml", false));

  // parse to XML then back to binary
  assertEquals(0, runOev(edits, editsParsedXml, "xml", true));
  assertEquals(0, runOev(editsParsedXml, editsReparsed, "binary", false));
  assertEquals(0, runOev(editsReparsed, editsParsedXml2, "xml", false));

  // judgment time
  assertTrue("Test round trip", FileUtils.contentEqualsIgnoreEOL(
      new File(editsParsedXml), new File(editsParsedXml2), "UTF-8"));

  os.close();
}
 
Example 11
Project: hadoop   File: FSImageFormatProtobuf.java   View Source Code Vote up 5 votes
void save(File file, FSImageCompression compression) throws IOException {
  FileOutputStream fout = new FileOutputStream(file);
  fileChannel = fout.getChannel();
  try {
    saveInternal(fout, compression, file.getAbsolutePath());
  } finally {
    fout.close();
  }
}
 
Example 12
Project: alfresco-repository   File: FileIOTest.java   View Source Code Vote up 5 votes
public void testConcurrentReadWrite() throws Exception
{
    // open file for a read
    FileInputStream isRead = new FileInputStream(file);
    // open file for write
    FileOutputStream osWrite = new FileOutputStream(file);
    
    // get channels
    FileChannel channelRead = isRead.getChannel();
    FileChannel channelWrite = osWrite.getChannel();
    
    // buffers
    ByteBuffer bufferRead = ByteBuffer.allocate(26);
    ByteBuffer bufferWrite = ByteBuffer.wrap(TEST_CONTENT.getBytes());
    
    // read - nothing will be read
    int countRead = channelRead.read(bufferRead);
    assertEquals("Expected nothing to be read", -1, countRead);
    // write
    int countWrite = channelWrite.write(bufferWrite);
    assertEquals("Not all characters written", 26, countWrite);
    
    // close the write side
    channelWrite.close();
    
    // reread
    countRead = channelRead.read(bufferRead);
    assertEquals("Expected full read", 26, countRead);
}
 
Example 13
Project: neoscada   File: DataFileAccessorImpl.java   View Source Code Vote up 5 votes
/**
 * Initialize a new file, write the empty structure to disk and return a new
 * accessor to it
 * 
 * @param file
 *            The file to create. This file must not exists.
 * @param startDate
 *            the start date of the file
 * @param endDate
 *            the end date of the file
 * @return a newly created file accessor
 * @throws Exception
 *             if anything goes wrong
 */
public static DataFileAccessorImpl create ( final File file, final Date startDate, final Date endDate ) throws Exception
{
    logger.debug ( "Creating new file: {}", file );

    if ( !file.createNewFile () )
    {
        throw new IllegalStateException ( String.format ( "Unable to create file %s, already exists", file ) );
    }

    final FileOutputStream out = new FileOutputStream ( file );

    try
    {
        final FileChannel channel = out.getChannel ();

        final ByteBuffer buffer = ByteBuffer.allocate ( 100 );
        buffer.putInt ( 0x1202 ); // magic marker
        buffer.putInt ( 0x0101 ); // version
        buffer.putLong ( startDate.getTime () ); // start timestamp
        buffer.putLong ( endDate.getTime () ); // end timestamp

        buffer.flip ();

        while ( buffer.hasRemaining () )
        {
            final int rc = channel.write ( buffer );
            logger.debug ( "Header written - {} bytes", rc );
        }

        return new DataFileAccessorImpl ( file );
    }
    finally
    {
        out.close ();
    }
}
 
Example 14
Project: live_master   File: SrsMp4Muxer.java   View Source Code Vote up 5 votes
private void createMovie(File outputFile) throws IOException {
    fos = new FileOutputStream(outputFile);
    fc = fos.getChannel();
    mdat = new InterleaveChunkMdat();
    mdatOffset = 0;

    FileTypeBox fileTypeBox = createFileTypeBox();
    fileTypeBox.getBox(fc);
    recFileSize += fileTypeBox.getSize();
}
 
Example 15
Project: IslamicLibraryAndroid   File: StorageUtils.java   View Source Code Vote up 5 votes
private static void copyFile(File source, File destination) throws IOException {
    FileInputStream inStream = new FileInputStream(source);
    FileOutputStream outStream = new FileOutputStream(destination);
    FileChannel inChannel = inStream.getChannel();
    FileChannel outChannel = outStream.getChannel();
    try {
        inChannel.transferTo(0, inChannel.size(), outChannel);
    } finally {
        inStream.close();
        outStream.close();
    }

}
 
Example 16
Project: CDN-FX-2.2   File: XMLHandler.java   View Source Code Vote up 5 votes
public void getXMLFileFromServer()
{

    if(PropertiesHandler.getProperties("disable3dsdbxml") != null)
    {
        if(PropertiesHandler.getProperties("disable3dsdbxml").equals("no"))
        {
            try
            {
                DebugLogger.log("INIT: Downloading 3dsdb newest XML database...", Level.INFO);
                File tempFile = File.createTempFile("3dsdb", Long.toString(System.nanoTime()));
                ReadableByteChannel in = Channels.newChannel(new URL("http://3dsdb.com/xml.php").openStream());
                FileOutputStream fos = new FileOutputStream(tempFile);
                FileChannel out = fos.getChannel();

                out.transferFrom(in, 0L, Long.MAX_VALUE);
                in.close();
                out.close();
                fos.close();

                this.pathToDB = tempFile.getPath();
                DebugLogger.log("INIT: Download completed!", Level.INFO);
            }
            catch (Exception e)
            {
                DebugLogger.log("INIT: Download failed! Using local file", Level.WARNING);
                getXMLFileFromJar();
            }
        }
    }
}
 
Example 17
Project: sstable-adaptor   File: BufferedDataOutputStreamPlus.java   View Source Code Vote up 4 votes
public BufferedDataOutputStreamPlus(FileOutputStream fos)
{
    this(fos.getChannel());
}
 
Example 18
Project: openjdk-jdk10   File: Transfer.java   View Source Code Vote up 4 votes
@Test
public void testFileChannel() throws Exception {
    File source = File.createTempFile("source", null);
    source.deleteOnExit();
    File sink = File.createTempFile("sink", null);
    sink.deleteOnExit();

    FileOutputStream fos = new FileOutputStream(source);
    FileChannel sourceChannel = fos.getChannel();
    sourceChannel.write(ByteBuffer.wrap(
        "Use the source, Luke!".getBytes()));
    sourceChannel.close();

    FileInputStream fis = new FileInputStream(source);
    sourceChannel = fis.getChannel();

    RandomAccessFile raf = new RandomAccessFile(sink, "rw");
    FileChannel sinkChannel = raf.getChannel();
    long oldSinkPosition = sinkChannel.position();
    long oldSourcePosition = sourceChannel.position();

    long bytesWritten = sinkChannel.transferFrom(sourceChannel, 0, 10);
    if (bytesWritten != 10)
        throw new RuntimeException("Transfer failed");

    if (sourceChannel.position() == oldSourcePosition)
        throw new RuntimeException("Source position didn't change");

    if (sinkChannel.position() != oldSinkPosition)
        throw new RuntimeException("Sink position changed");

    if (sinkChannel.size() != 10)
        throw new RuntimeException("Unexpected sink size");

    bytesWritten = sinkChannel.transferFrom(sourceChannel, 1000, 10);

    if (bytesWritten > 0)
        throw new RuntimeException("Wrote past file size");

    sourceChannel.close();
    sinkChannel.close();

    source.delete();
    sink.delete();
}
 
Example 19
Project: incubator-netbeans   File: CacheWriter.java   View Source Code Vote up 4 votes
public void write (BufferedImage img, boolean append, String id) throws IOException {
    File out = getOutfile(append);
    File meta = getMetafile(append);
    System.err.println("Writing to " + out + " and " + meta);
    
    int width = img.getWidth();
    int height = img.getHeight();
    
    ByteBuffer buf = ByteBuffer.allocate(width * height * 4);
    IntBuffer ibuf = buf.asIntBuffer();
  
    for (int y=0; y < height; y++) {
        for (int x=0; x < width; x++) {
            int pixel = img.getRGB(x, y);
            ibuf.put(pixel);
        }
    }
    FileOutputStream fileOut = new FileOutputStream (out, append);
    FileOutputStream metaOut = new FileOutputStream (meta, append);
    FileChannel fileChannel = fileOut.getChannel();
    
    if (append) {
        fileChannel.position(out.length());
    }
    
    //Check the size of the file we're creating - nio bytebuffers are
    //limited to dealing with files < Integer.MAX_VALUE large
    if (fileChannel.position() + buf.limit() > Integer.MAX_VALUE) {
        //Can handle this and create a second cache file in the unlikely
        //event this comes to pass
        throw new BufferOverflowException();
    }
    
    long start = fileChannel.position();
    
    fileChannel.write(buf);
    
    long end = fileChannel.position();
    
    fileChannel.force(true);
    fileChannel.close();
    
    FileChannel metaChannel = metaOut.getChannel();
    if (append) {
        metaChannel.position(meta.length());
    }
    
    metaChannel.write(getMetadata(img, id, start, end));
    metaChannel.force(true);
    metaChannel.close();
}
 
Example 20
Project: Rey-MusicPlayer   File: FileUtils.java   View Source Code Vote up 4 votes
public static void cutFile(File sourceFile, File destFile) throws IOException {

        FileChannel destination = null;
        FileChannel source = null;
        ParcelFileDescriptor pfd = null;
        try {
            source = new FileInputStream(sourceFile).getChannel();

            if (MusicUtils.isFromSdCard(destFile.getAbsolutePath())) {
                DocumentFile documentFile = FileUtils.getDocumentFile(destFile);
                pfd = Common.getInstance().getContentResolver().openFileDescriptor(documentFile.getUri(), "w");
                FileOutputStream outputStream = new FileOutputStream(pfd.getFileDescriptor());
                destination = outputStream.getChannel();
            } else {
                destination = new FileOutputStream(destFile).getChannel();
            }


            if (!destFile.getParentFile().exists())
                destFile.getParentFile().mkdirs();

            if (!destFile.exists()) {
                destFile.createNewFile();
            }


            destination.transferFrom(source, 0, source.size());

        } catch (Exception e) {
            e.printStackTrace();
            Logger.log("MESSAGE -" + e.getMessage() + "CAUSE " + e.getCause());
        } finally {
            deleteRecursive(sourceFile);
            if (pfd != null) {
                pfd.close();
            }
            if (source != null) {
                source.close();
            }
            if (destination != null) {
                destination.close();
            }
        }
    }