java.io.FileOutputStream#getChannel ( )源码实例Demo

下面列出了java.io.FileOutputStream#getChannel ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: jpHolo   文件: LocalFilesystem.java
/**
 * 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();
    }
}
 
源代码2 项目: tickmate   文件: FileUtils.java
/**
 * 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();
            }
        }
    }
}
 
源代码3 项目: gemfirexd-oss   文件: GFSnapshot.java
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);
}
 
/**
 * 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);
    }
}
 
源代码5 项目: VideoCompressor   文件: MP4Builder.java
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;
}
 
源代码6 项目: symja_android_library   文件: IOUtilities.java
/**
 * 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);
    }
}
 
源代码7 项目: gemfirexd-oss   文件: FileUtil.java
/**
 * 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;
    }
  }
}
 
源代码8 项目: Telegram-FOSS   文件: MP4Builder.java
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;
}
 
源代码9 项目: pentaho-kettle   文件: IngresVectorwiseLoader.java
public void run() {
  try {

    fileOutputStream = new FileOutputStream( this.fifoName );
    fileChannel = fileOutputStream.getChannel();
  } catch ( Exception ex ) {
    this.ex = ex;
  }
}
 
源代码10 项目: mp4parser   文件: MuxVideoWithAmf0.java
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();

}
 
源代码11 项目: mp4parser   文件: Ec3Example.java
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();
}
 
源代码12 项目: jmeter-plugins   文件: FlexibleFileWriter.java
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()));
    }
}
 
源代码13 项目: netty-4.1.22   文件: AbstractDiskHttpData.java
@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();
}
 
源代码14 项目: crail   文件: LogService.java
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>();
}
 
源代码15 项目: Aria   文件: SFtpDThreadTaskAdapter.java
/**
 * 下载
 */
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();
}
 
源代码16 项目: localization_nifi   文件: FileUtils.java
/**
 * 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);
    }
}
 
源代码17 项目: j2objc   文件: FileChannelTest.java
/**
 * @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());
}
 
源代码18 项目: emerald   文件: FileUtils.java
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();
	}
}
 
源代码19 项目: java-core-learning-example   文件: FileChannelT.java
@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));
}
 
源代码20 项目: Common   文件: FileUtils.java
/**
 * 快速复制文件(采用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);
}