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

The following examples show how to use java.io.FileOutputStream#getChannel() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MockInitialContextFactory.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Copies a resource inside a jar to external file within a directory.
 * Then returns the created file.
 *
 * @param relativeFilePath
 * @param clazz
 * @return
 * @throws TestCreationException
 */
private static File copyTempFile(String relativeFilePath, Class clazz) throws TestCreationException {

    URL url = clazz.getClassLoader().getResource(relativeFilePath);
    if(url == null) {
        throw new TestCreationException("Could not find a resource on the classpath : " + relativeFilePath);
    }
    InputStream inputStream;
    try {
        inputStream = url.openStream();
        ReadableByteChannel inputChannel = Channels.newChannel(inputStream);
        File tempFile = File.createTempFile("tmp_", "_registry.sql");
        FileOutputStream fos = new FileOutputStream(tempFile);
        WritableByteChannel targetChannel = fos.getChannel();
        //Transfer data from input channel to output channel
        ((FileChannel) targetChannel).transferFrom(inputChannel, 0, Short.MAX_VALUE);
        inputStream.close();
        targetChannel.close();
        fos.close();
        return tempFile;
    } catch (IOException e) {
        throw new TestCreationException("Could not copy the file content to temp file from : " + relativeFilePath);
    }
}
 
Example 2
Source File: MP4Builder.java    From Telegram-FOSS with GNU General Public License v2.0 6 votes vote down vote up
public MP4Builder createMovie(Mp4Movie mp4Movie, boolean split) throws Exception {
    currentMp4Movie = mp4Movie;

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

    FileTypeBox fileTypeBox = createFileTypeBox();
    fileTypeBox.getBox(fc);
    dataOffset += fileTypeBox.getSize();
    wroteSinceLastMdat += dataOffset;
    splitMdat = split;

    mdat = new InterleaveChunkMdat();

    sizeBuffer = ByteBuffer.allocateDirect(4);

    return this;
}
 
Example 3
Source File: FileUtil.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Copy a single file using NIO.
 * @throws IOException
 */
private static void nioCopy(FileOutputStream fos, FileInputStream fis)
    throws IOException {
  FileChannel outChannel = fos.getChannel();
  FileChannel inChannel = fis.getChannel();
  long length = inChannel.size();
  long offset = 0;
  while(true) {
    long remaining = length - offset;
    
    long toTransfer = remaining < MAX_TRANSFER_SIZE ? remaining : MAX_TRANSFER_SIZE;
    long transferredBytes = inChannel.transferTo(offset, toTransfer, outChannel);
    offset += transferredBytes;
    length = inChannel.size();
    if(offset >= length) {
      break;
    }
  }
}
 
Example 4
Source File: IOUtilities.java    From symja_android_library with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Version of {@link #transfer(InputStream, OutputStream)} for File streams that uses
 * NIO to do a hopefully more efficient transfer.
 */
public static void transfer(FileInputStream fileInStream, FileOutputStream fileOutStream)
        throws IOException {
    FileChannel fileInChannel = fileInStream.getChannel();
    FileChannel fileOutChannel = fileOutStream.getChannel();
    long fileInSize = fileInChannel.size();
    try {
        long transferred = fileInChannel.transferTo(0, fileInSize, fileOutChannel);
        if (transferred!=fileInSize) {
            /* Hmmm... need to rethink this algorithm if something goes wrong */
            throw new IOException("transfer() did not complete");
        }
    }
    finally {
        ensureClose(fileInChannel, fileOutChannel);
    }
}
 
Example 5
Source File: MP4Builder.java    From VideoCompressor with Apache License 2.0 6 votes vote down vote up
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
Source File: GFSnapshot.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
public GFSnapshotExporter(File out, String region) throws IOException {
  FileOutputStream fos = new FileOutputStream(out);
  fc = fos.getChannel();
  
  dos = new DataOutputStream(new BufferedOutputStream(fos));
  
  // write snapshot version
  dos.writeByte(SNAP_VER_2);
  
  // write format type
  dos.write(SNAP_FMT);
  
  // write temporary pdx location in bytes 4-11
  dos.writeLong(-1);

  // write region name
  dos.writeUTF(region);
}
 
Example 7
Source File: FileUtils.java    From tickmate with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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 8
Source File: LocalFilesystem.java    From jpHolo with MIT License 6 votes vote down vote up
/**
 * Moved this code into it's own method so moveTo could use it when the move is across file systems
 */
private void copyAction(File srcFile, File destFile)
        throws FileNotFoundException, IOException {
    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();
    }
}
 
Example 9
Source File: AbstractDiskHttpData.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
public void setContent(InputStream inputStream) throws IOException {
    if (inputStream == null) {
        throw new NullPointerException("inputStream");
    }
    if (file != null) {
        delete();
    }
    file = tempFile();
    FileOutputStream outputStream = new FileOutputStream(file);
    int written = 0;
    try {
        FileChannel localfileChannel = outputStream.getChannel();
        byte[] bytes = new byte[4096 * 4];
        ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
        int read = inputStream.read(bytes);
        while (read > 0) {
            byteBuffer.position(read).flip();
            written += localfileChannel.write(byteBuffer);
            checkSize(written);
            read = inputStream.read(bytes);
        }
        localfileChannel.force(false);
    } finally {
        outputStream.close();
    }
    size = written;
    if (definedSize > 0 && definedSize < size) {
        if (!file.delete()) {
            logger.warn("Failed to delete: {}", file);
        }
        file = null;
        throw new IOException("Out of size: " + size + " > " + definedSize);
    }
    isRenamed = true;
    setCompleted();
}
 
Example 10
Source File: LogService.java    From crail with Apache License 2.0 5 votes vote down vote up
public LogService() throws IOException {
	File file = new File(CrailConstants.NAMENODE_LOG);
	if (!file.exists()){
		file.createNewFile();
	}
	outStream = new FileOutputStream(CrailConstants.NAMENODE_LOG, true);
	outChannel = outStream.getChannel();
	header = ByteBuffer.allocate(4);
	payload = ByteBuffer.allocate(512);
	tokens = new ConcurrentHashMap<Long, Long>();
}
 
Example 11
Source File: IngresVectorwiseLoader.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
public void run() {
  try {

    fileOutputStream = new FileOutputStream( this.fifoName );
    fileChannel = fileOutputStream.getChannel();
  } catch ( Exception ex ) {
    this.ex = ex;
  }
}
 
Example 12
Source File: SFtpDThreadTaskAdapter.java    From Aria with Apache License 2.0 5 votes vote down vote up
/**
 * 下载
 */
private void download(String remotePath) throws SftpException, IOException {
  InputStream is =
      channelSftp.get(remotePath, new Monitor(), getThreadRecord().startLocation);
  FileOutputStream fos = new FileOutputStream(getThreadConfig().tempFile, true);
  FileChannel foc = fos.getChannel();
  ReadableByteChannel fic = Channels.newChannel(is);
  ByteBuffer bf = ByteBuffer.allocate(getTaskConfig().getBuffSize());
  int len;
  while (getThreadTask().isLive() && (len = fic.read(bf)) != -1) {
    if (getThreadTask().isBreak()) {
      break;
    }
    if (mSpeedBandUtil != null) {
      mSpeedBandUtil.limitNextBytes(len);
    }
    if (getRangeProgress() + len >= getThreadRecord().endLocation) {
      len = (int) (getThreadRecord().endLocation - getRangeProgress());
      bf.flip();
      fos.write(bf.array(), 0, len);
      bf.compact();
      progress(len);
      break;
    } else {
      bf.flip();
      foc.write(bf);
      bf.compact();
      progress(len);
    }
  }
  fos.flush();
  fos.close();
  is.close();
}
 
Example 13
Source File: FlexibleFileWriter.java    From jmeter-plugins with Apache License 2.0 5 votes vote down vote up
protected void openFile() throws IOException {
    String filename = getFilename();
    FileOutputStream fos = new FileOutputStream(filename, !isOverwrite());
    fileChannel = fos.getChannel();

    String header = JMeterPluginsUtils.replaceRNT(getFileHeader());
    if (!header.isEmpty()) {
        syncWrite(ByteBuffer.wrap(header.getBytes()));
    }
}
 
Example 14
Source File: FileUtils.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Randomly generates a sequence of bytes and overwrites the contents of the file a number of times. The file is then deleted.
 *
 * @param file File to be overwritten a number of times and, ultimately, deleted
 * @param passes Number of times file should be overwritten
 * @throws IOException if something makes shredding or deleting a problem
 */
public static void shredFile(final File file, final int passes)
        throws IOException {
    final Random generator = new Random();
    final long fileLength = file.length();
    final int byteArraySize = (int) Math.min(fileLength, 1048576); // 1MB
    final byte[] b = new byte[byteArraySize];
    final long numOfRandomWrites = (fileLength / b.length) + 1;
    final FileOutputStream fos = new FileOutputStream(file);
    try {
        // Over write file contents (passes) times
        final FileChannel channel = fos.getChannel();
        for (int i = 0; i < passes; i++) {
            generator.nextBytes(b);
            for (int j = 0; j <= numOfRandomWrites; j++) {
                fos.write(b);
            }
            fos.flush();
            channel.position(0);
        }
        // Write out "0" for each byte in the file
        Arrays.fill(b, (byte) 0);
        for (int j = 0; j < numOfRandomWrites; j++) {
            fos.write(b);
        }
        fos.flush();
        fos.close();
        // Try to delete the file a few times
        if (!FileUtils.deleteFile(file, null, 5)) {
            throw new IOException("Failed to delete file after shredding");
        }

    } finally {
        FileUtils.closeQuietly(fos);
    }
}
 
Example 15
Source File: FileChannelTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * @tests java.nio.channels.FileChannel#isOpen()
 */
public void test_isOpen() throws Exception {
    // Regression for HARMONY-40
    File logFile = File.createTempFile("out", "tmp");
    logFile.deleteOnExit();
    FileOutputStream out = new FileOutputStream(logFile, true);
    FileChannel channel = out.getChannel();
    out.write(1);
    out.close();
    assertFalse("Assert 0: Channel is still open", channel.isOpen());
}
 
Example 16
Source File: FileUtils.java    From emerald with GNU General Public License v3.0 5 votes vote down vote up
public static void copy(Context context, File source, File dest) {
	try {
		FileInputStream fis = new FileInputStream(source);
		FileOutputStream fos = new FileOutputStream(dest);
		FileChannel src = fis.getChannel();
		FileChannel dst = fos.getChannel();
		dst.transferFrom(src, 0, src.size());
		src.close();
		dst.close();
		fis.close();
		fos.close();
	} catch (Exception e) {
		Toast.makeText(context, e.toString(), Toast.LENGTH_LONG).show();
	}
}
 
Example 17
Source File: Ec3Example.java    From mp4parser with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
    EC3TrackImpl track = new EC3TrackImpl(new FileDataSourceImpl("C:\\Users\\sannies\\Downloads\\audio.ac3"));
    Movie m = new Movie();
    m.addTrack(track);
    DefaultMp4Builder mp4Builder = new DefaultMp4Builder();
    Container isoFile = mp4Builder.build(m);
    FileOutputStream fos = new FileOutputStream("output.mp4");
    FileChannel fc = fos.getChannel();
    isoFile.writeContainer(fc);
    fos.close();
}
 
Example 18
Source File: MuxVideoWithAmf0.java    From mp4parser with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
    String videoFile = MuxVideoWithAmf0.class.getProtectionDomain().getCodeSource().getLocation().getFile() + "/example-sans-amf0.mp4";

    Movie video = MovieCreator.build(videoFile);

    Properties props = new Properties();
    props.load(MuxVideoWithAmf0.class.getResourceAsStream("/amf0track.properties"));
    HashMap<Long, byte[]> samples = new HashMap<Long, byte[]>();
    for (String key : props.stringPropertyNames()) {
        samples.put(Long.parseLong(key), Base64.decodeBase64(props.getProperty(key)));
    }
    Track amf0Track = new Amf0Track(samples);
    amf0Track.getTrackMetaData();
    video.addTrack(amf0Track);

    FragmentedMp4Builder fragmentedMp4Builder = new FragmentedMp4Builder();
    fragmentedMp4Builder.setFragmenter(new DefaultFragmenterImpl(2));

    Container out = fragmentedMp4Builder.build(video);
    FileOutputStream fos = new FileOutputStream(new File(String.format("output.mp4")));

    FileChannel fc = fos.getChannel();
    out.writeContainer(fc);

    fos.close();

}
 
Example 19
Source File: FileChannelT.java    From java-core-learning-example with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("resource")
public static void main(String[] args) throws IOException {
	// NIO包路径
	String dir = "src" + File.separator +
			"org" + File.separator +
			"javacore" + File.separator +
			"nio";
	// 获取FileChannelT.java文件,读写方式
	RandomAccessFile inFile = new RandomAccessFile(dir + File.separator + 
			"FileChannelT.java","rw");
	// 创建输出文件流
	FileOutputStream outFileStream = new FileOutputStream("D:\\FileChannelT2.java");
	// 创建输入文件通道
	FileChannel inChannel = inFile.getChannel();
	// 创建输出文件通道
	FileChannel outChannel = outFileStream.getChannel();
	// 分配一个1024字节的字节缓存区
	ByteBuffer byteBuffer = ByteBuffer.allocateDirect(1024); // 比allocate();效率高
	
	// 测试时间
	long startTime = System.currentTimeMillis();
	
	// 读文件,存文件
	while (true) {
		// 将字节序列从此通道读入给定的缓冲区
		int eof = inChannel.read(byteBuffer);
		// 读到文件末尾退出
		if (eof == -1) 
			break;
		// 反转缓冲区
		byteBuffer.flip();
		// 将字节序列从给定的缓冲区写入此通道
		outChannel.write(byteBuffer);
		// 清空缓存区
		byteBuffer.clear();
	}
	inChannel.close();
	outChannel.close();
	
	System.out.println("耗时:" + (System.currentTimeMillis() - startTime));
}
 
Example 20
Source File: FileUtils.java    From Common with Apache License 2.0 3 votes vote down vote up
/**
 * 快速复制文件(采用nio操作)
 *
 * @param is 数据来源
 * @param os 数据目标
 * @throws IOException
 */
public static void copyFileFast(FileInputStream is, FileOutputStream os)
        throws IOException {
    FileChannel in = is.getChannel();
    FileChannel out = os.getChannel();
    in.transferTo(0, in.size(), out);
}