Java Code Examples for java.nio.channels.FileChannel#close()

The following examples show how to use java.nio.channels.FileChannel#close() . 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: MetaDataInsert.java    From mp4parser with Apache License 2.0 6 votes vote down vote up
public FileChannel splitFileAndInsert(File f, long pos, long length) throws IOException {
    FileChannel read = new RandomAccessFile(f, "r").getChannel();
    File tmp = File.createTempFile("ChangeMetaData", "splitFileAndInsert");
    FileChannel tmpWrite = new RandomAccessFile(tmp, "rw").getChannel();
    read.position(pos);
    tmpWrite.transferFrom(read, 0, read.size() - pos);
    read.close();
    FileChannel write = new RandomAccessFile(f, "rw").getChannel();
    write.position(pos + length);
    tmpWrite.position(0);
    long transferred = 0;
    while ((transferred += tmpWrite.transferTo(0, tmpWrite.size() - transferred, write)) != tmpWrite.size()) {
        System.out.println(transferred);
    }
    System.out.println(transferred);
    tmpWrite.close();
    tmp.delete();
    return write;
}
 
Example 2
Source File: MyFiles.java    From fnlp with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 合并文件
 * @param saveFileName
 * @param files
 * @throws Exception
 */
public static void combine(String saveFileName, String... files) throws Exception{
	File mFile=new File(saveFileName); 

	if(!mFile.exists()){ 
		mFile.createNewFile(); 
	} 
	
	FileOutputStream os = new FileOutputStream(mFile);
	FileChannel mFileChannel = os.getChannel(); 
	FileChannel inFileChannel; 
	for(String file:files){
		File f = new File(file);
		if(!f.exists())
			continue;
		inFileChannel=new FileInputStream(f).getChannel(); 
		inFileChannel.transferTo(0, inFileChannel.size(), mFileChannel); 

		inFileChannel.close(); 
	} 

	mFileChannel.close(); 
	os.close();
}
 
Example 3
Source File: FontItemContainer.java    From Quran-For-My-Android with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("resource")
public static void addNewFile(File sourceFile) throws IOException{
	FileChannel source = null;
	FileChannel destination = null;
	
	File destFile=new File(fontStorageDir,sourceFile.getName());
	
	destFile.createNewFile();

	source=new FileInputStream(sourceFile).getChannel();
	destination=new FileOutputStream(destFile).getChannel();

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

		
	try{
		if(source!=null) source.close();
		if(destination!=null)destination.close();
	}catch(IOException ie){ie.printStackTrace();}
}
 
Example 4
Source File: HTTPRawSampler.java    From jmeter-plugins with Apache License 2.0 6 votes vote down vote up
private void sendFile(String filename, SocketChannel sock) throws IOException {
    if (filename.isEmpty()) {
        return;
    }
    
    FileInputStream is = new FileInputStream(new File(filename));
    FileChannel source = is.getChannel();
    
    ByteBuffer sendBuf = ByteBuffer.allocateDirect(fileSendingChunk);
    while (source.read(sendBuf) > 0) {
        sendBuf.flip();
        if (log.isDebugEnabled()) {
            log.debug("Sending " + sendBuf);
        }
        sock.write(sendBuf);
        sendBuf.rewind();
    }
    
    source.close();
}
 
Example 5
Source File: LocalFilesystem.java    From reader 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 6
Source File: IntArraySerializer.java    From imhotep with Apache License 2.0 6 votes vote down vote up
@Override
public void serialize(int[] a, File file) throws IOException {
    FileChannel ch = new RandomAccessFile(file, "rw").getChannel();
    try {
        ByteBuffer buffer = ByteBuffer.allocateDirect(8192);
        buffer.order(ByteOrder.LITTLE_ENDIAN);
        IntBuffer intBuffer = buffer.asIntBuffer();
        for (int i = 0; i < a.length; i += 2048) {
            intBuffer.clear();
            int lim = Math.min(2048, a.length - i);
            intBuffer.put(a, i, lim);
            buffer.position(0).limit(4*lim);
            ch.write(buffer);
        }
    } finally {
        ch.close();
    }
}
 
Example 7
Source File: FileUtils.java    From Android-Skin with MIT License 6 votes vote down vote up
public static void copyFile(File src, File dest) throws IOException {
    FileChannel inChannel = null;
    FileChannel outChannel = null;

    try {
        if (!dest.exists()) {
            dest.createNewFile();
        }

        inChannel = (new FileInputStream(src)).getChannel();
        outChannel = (new FileOutputStream(dest)).getChannel();
        inChannel.transferTo(0L, inChannel.size(), outChannel);
    } finally {
        if (inChannel != null) {
            inChannel.close();
        }

        if (outChannel != null) {
            outChannel.close();
        }

    }

}
 
Example 8
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 9
Source File: Lobstack.java    From jelectrum with MIT License 6 votes vote down vote up
public synchronized void close()
  throws IOException
{
  root_file_channel.force(true);
  root_file_channel.close();

  synchronized(data_files)
  {
    for(FileChannel fc : data_files.values())
    {
      fc.force(true);
      fc.close();
    }
  }

}
 
Example 10
Source File: Util.java    From whyline with MIT License 5 votes vote down vote up
public static void copyFile(File source, File dest) throws IOException {

		if(!source.exists()) return;
		if(!dest.exists()) {
			dest.getParentFile().mkdirs();
			dest.createNewFile();
		}
		
        FileChannel srcChannel = new FileInputStream(source).getChannel();
        FileChannel dstChannel = new FileOutputStream(dest).getChannel();
        dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
        srcChannel.close();
        dstChannel.close();

	}
 
Example 11
Source File: TestVerboseFS.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/** Test FileChannel.open */
public void testFileChannel() throws IOException {
  InfoStreamListener stream = new InfoStreamListener("newFileChannel");
  Path dir = wrap(createTempDir(), stream);
  FileChannel channel = FileChannel.open(dir.resolve("foobar"), StandardOpenOption.CREATE_NEW, StandardOpenOption.READ, StandardOpenOption.WRITE);
  assertTrue(stream.sawMessage());
  channel.close();

  expectThrows(IOException.class, () -> FileChannel.open(dir.resolve("foobar"),
      StandardOpenOption.CREATE_NEW, StandardOpenOption.READ, StandardOpenOption.WRITE));
}
 
Example 12
Source File: CoreWorkBench.java    From document-management-software with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static void copyFileUsingChannel(File source, File dest) throws IOException {
	FileChannel sourceChannel = null;
	FileChannel destChannel = null;
	try {
		sourceChannel = new FileInputStream(source).getChannel();
		destChannel = new FileOutputStream(dest).getChannel();
		destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
	} finally {
		sourceChannel.close();
		destChannel.close();
	}
}
 
Example 13
Source File: CheckZombieLockTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Setup all the files and directories needed for the tests
 *
 * @return writable directory created that needs to be deleted when done
 * @throws RuntimeException
 */
private static File setup() throws RuntimeException {
    // First do some setup in the temporary directory (using same logic as
    // FileHandler for %t pattern)
    String tmpDir = System.getProperty("java.io.tmpdir"); // i.e. %t
    if (tmpDir == null) {
        tmpDir = System.getProperty("user.home");
    }
    File tmpOrHomeDir = new File(tmpDir);
    // Create a writable directory here (%t/writable-lockfile-dir)
    File writableDir = new File(tmpOrHomeDir, WRITABLE_DIR);
    if (!createFile(writableDir, true)) {
        throw new RuntimeException("Test setup failed: unable to create"
                + " writable working directory "
                + writableDir.getAbsolutePath() );
    }

    // try to determine whether file locking is supported
    final String uniqueFileName = UUID.randomUUID().toString()+".lck";
    try {
        FileChannel fc = FileChannel.open(Paths.get(writableDir.getAbsolutePath(),
                uniqueFileName),
                StandardOpenOption.CREATE_NEW, StandardOpenOption.APPEND,
                StandardOpenOption.DELETE_ON_CLOSE);
        try {
            fc.tryLock();
        } catch(IOException x) {
            supportsLocking = false;
        } finally {
            fc.close();
        }
    } catch (IOException t) {
        // should not happen
        System.err.println("Failed to create new file " + uniqueFileName +
                " in " + writableDir.getAbsolutePath());
        throw new RuntimeException("Test setup failed: unable to run test", t);
    }
    return writableDir;
}
 
Example 14
Source File: FileUtils.java    From FastCopy with Apache License 2.0 5 votes vote down vote up
private static void copyFileUsingFileChannels(File source, File dest)
		throws IOException {
	FileChannel inputChannel = null;
	FileChannel outputChannel = null;
	try {
		inputChannel = new FileInputStream(source).getChannel();
		outputChannel = new FileOutputStream(dest).getChannel();
		outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
	} finally {
		inputChannel.close();
		outputChannel.close();
	}
}
 
Example 15
Source File: SolarisUserDefinedFileAttributeView.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public int read(String name, ByteBuffer dst) throws IOException {
    if (System.getSecurityManager() != null)
        checkAccess(file.getPathForPermissionCheck(), true, false);

    int fd = file.openForAttributeAccess(followLinks);
    try {
        try {
            // open attribute file
            int afd = openat(fd, nameAsBytes(file,name), (O_RDONLY|O_XATTR), 0);

            // wrap with channel
            FileChannel fc = UnixChannelFactory.newFileChannel(afd, file.toString(), true, false);

            // read to EOF (nothing we can do if I/O error occurs)
            try {
                if (fc.size() > dst.remaining())
                    throw new IOException("Extended attribute file too large");
                int total = 0;
                while (dst.hasRemaining()) {
                    int n = fc.read(dst);
                    if (n < 0)
                        break;
                    total += n;
                }
                return total;
            } finally {
                fc.close();
            }
        } catch (UnixException x) {
            throw new FileSystemException(file.getPathForExceptionMessage(),
                null, "Unable to read extended attribute '" + name +
                "': " + x.getMessage());
        }
    } finally {
        close(fd);
    }
}
 
Example 16
Source File: SolarisUserDefinedFileAttributeView.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
@Override
public int write(String name, ByteBuffer src) throws IOException {
    if (System.getSecurityManager() != null)
        checkAccess(file.getPathForPermissionCheck(), false, true);

    int fd = file.openForAttributeAccess(followLinks);
    try {
        try {
            // open/create attribute file
            int afd = openat(fd, nameAsBytes(file,name),
                             (O_CREAT|O_WRONLY|O_TRUNC|O_XATTR),
                             UnixFileModeAttribute.ALL_PERMISSIONS);

            // wrap with channel
            FileChannel fc = UnixChannelFactory.newFileChannel(afd, false, true);

            // write value (nothing we can do if I/O error occurs)
            try {
                int rem = src.remaining();
                while (src.hasRemaining()) {
                    fc.write(src);
                }
                return rem;
            } finally {
                fc.close();
            }
        } catch (UnixException x) {
            throw new FileSystemException(file.getPathForExceptionMessage(),
                null, "Unable to write extended attribute '" + name +
                "': " + x.getMessage());
        }
    } finally {
        close(fd);
    }
}
 
Example 17
Source File: FileUtil.java    From GTTools with MIT License 5 votes vote down vote up
/**
 * 文件管道的关闭
 * 
 * @param chl
 */
public static void closeFileChannel(FileChannel chl) {
	if (chl != null) {
		try {
			chl.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
 
Example 18
Source File: LogTelnetHandler.java    From dubbox with Apache License 2.0 4 votes vote down vote up
public String telnet(Channel channel, String message) {
    long size = 0 ;
    File file = LoggerFactory.getFile();
    StringBuffer buf = new StringBuffer();
    if (message == null || message.trim().length() == 0) {
        buf.append("EXAMPLE: log error / log 100");
    }else {
        String str[] = message.split(" ");
        if (! StringUtils.isInteger(str[0])){
            LoggerFactory.setLevel(Level.valueOf(message.toUpperCase()));
        } else {
            int SHOW_LOG_LENGTH = Integer.parseInt(str[0]);
            
            if (file != null && file.exists()) {
                try{
                    FileInputStream fis = new FileInputStream(file);
                    try {
                     FileChannel filechannel = fis.getChannel();
                     try {
                      size = filechannel.size();
                      ByteBuffer bb;
                      if (size <= SHOW_LOG_LENGTH) {
                          bb = ByteBuffer.allocate((int) size);
                          filechannel.read(bb, 0);
                      } else {
                          int pos = (int) (size - SHOW_LOG_LENGTH);
                          bb = ByteBuffer.allocate(SHOW_LOG_LENGTH);
                          filechannel.read(bb, pos);
                      }
                      bb.flip();
                      String content = new String(bb.array()).replace("<", "&lt;")
                      .replace(">", "&gt;").replace("\n", "<br/><br/>");
                      buf.append("\r\ncontent:"+content);
                      
                      buf.append("\r\nmodified:"+(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                      .format(new Date(file.lastModified()))));
                      buf.append("\r\nsize:"+size +"\r\n");
                     } finally {
                     	filechannel.close();
                     }
                    } finally {
                    	fis.close();
                    }
                }catch (Exception e) {
                    buf.append(e.getMessage());
                }
            }else {
                size = 0;
                buf.append("\r\nMESSAGE: log file not exists or log appender is console .");
            }
        }
    }
    buf.append("\r\nCURRENT LOG LEVEL:"+ LoggerFactory.getLevel())
    .append("\r\nCURRENT LOG APPENDER:"+ (file == null ? "console" : file.getAbsolutePath()));
    return buf.toString();
}
 
Example 19
Source File: Pwrite.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
private static void genericTest() throws Exception {
    StringBuffer sb = new StringBuffer();
    sb.setLength(4);

    blah = File.createTempFile("blah", null);
    blah.deleteOnExit();
    initTestFile(blah);

    RandomAccessFile raf = new RandomAccessFile(blah, "rw");
    FileChannel c = raf.getChannel();

    for (int x=0; x<100; x++) {
        long offset = generator.nextInt(1000);
        ByteBuffer bleck = ByteBuffer.allocateDirect(4);

        // Write known sequence out
        for (byte i=0; i<4; i++) {
            bleck.put(i);
        }
        bleck.flip();
        long originalPosition = c.position();
        int totalWritten = 0;
        while (totalWritten < 4) {
            int written = c.write(bleck, offset);
            if (written < 0)
                throw new Exception("Read failed");
            totalWritten += written;
        }

        long newPosition = c.position();

        // Ensure that file pointer position has not changed
        if (originalPosition != newPosition)
            throw new Exception("File position modified");

        // Attempt to read sequence back in
        bleck = ByteBuffer.allocateDirect(4);
        originalPosition = c.position();
        int totalRead = 0;
        while (totalRead < 4) {
            int read = c.read(bleck, offset);
            if (read < 0)
                throw new Exception("Read failed");
            totalRead += read;
        }
        newPosition = c.position();

        // Ensure that file pointer position has not changed
        if (originalPosition != newPosition)
            throw new Exception("File position modified");

        for (byte i=0; i<4; i++) {
            if (bleck.get(i) != i)
                throw new Exception("Write test failed");
        }
    }
    c.close();
    raf.close();
    blah.delete();
}
 
Example 20
Source File: IntegrationUtils.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public static boolean backupFile(File file) {
    File source = new File(file.getAbsolutePath());
    File target = new File(source.getAbsolutePath() + FILE_BACKUP_EXTENSION);

    if (!source.exists()) {
        ProfilerLogger.severe(MessageFormat.format(BACKUP_FILE_NOT_FOUND_MESSAGE, new Object[] { source.getAbsolutePath() })); //NOI18N

        return false;
    }

    if (target.exists()) {
        if (!target.delete()) {
            ProfilerLogger.severe(MessageFormat.format(BACKUP_CANNOT_DELETE_FILE_MESSAGE,
                                                       new Object[] { target.getAbsolutePath() })); //NOI18N

            return false;
        }
    }

    // move source to target to correctly preserve file permissions
    if (!source.renameTo(target)) {
        ProfilerLogger.severe(MessageFormat.format(BACKUP_ERROR_MESSAGE,
                                                   new Object[] { source.getAbsolutePath(), target.getAbsolutePath() })); //NOI18N

        return false;
    }

    // re-create source file for further processing
    try {
        source = new File(file.getAbsolutePath());
        source.createNewFile();
        target = new File(source.getAbsolutePath() + FILE_BACKUP_EXTENSION);

        FileChannel sourceChannel = new FileOutputStream(source).getChannel();
        try {
            FileChannel targetChannel = new FileInputStream(target).getChannel();
            try {
                targetChannel.transferTo(0, targetChannel.size(), sourceChannel);
                return true;
            } finally {
                targetChannel.close();
            }
        } finally {
            sourceChannel.close();
        }
    } catch (Exception ex) {
        ProfilerLogger.severe(MessageFormat.format(BACKUP_ERROR_COPY_FILE_MESSAGE,
                                                   new Object[] { target.getAbsolutePath(), source.getAbsolutePath(), ex })); //NOI18N

        return false;
    }
}