Example usage for java.nio.channels FileChannel close

List of usage examples for java.nio.channels FileChannel close

Introduction

In this page you can find the example usage for java.nio.channels FileChannel close.

Prototype

public final void close() throws IOException 

Source Link

Document

Closes this channel.

Usage

From source file:MainClass.java

public static void main(String[] args) throws IOException {

    FileInputStream inFile = new FileInputStream(args[0]);
    FileOutputStream outFile = new FileOutputStream(args[1]);

    FileChannel inChannel = inFile.getChannel();
    FileChannel outChannel = outFile.getChannel();

    ByteBuffer buffer = ByteBuffer.allocate(1024 * 1024);
    int bytesRead = 0;
    while (bytesRead >= 0 || buffer.hasRemaining()) {
        if (bytesRead != -1)
            bytesRead = inChannel.read(buffer);
        buffer.flip();//from w  w  w .  ja v  a2s .  com
        outChannel.write(buffer);
        buffer.compact();
    }

    inChannel.close();
    outChannel.close();
}

From source file:MainClass.java

public static void main(String args[]) {
    FileInputStream fileInputStream;
    FileChannel fileChannel;
    long fileSize;
    MappedByteBuffer mBuf;//from w w w.  j av a  2 s  .  c  o  m

    try {
        fileInputStream = new FileInputStream("test.txt");
        fileChannel = fileInputStream.getChannel();
        fileSize = fileChannel.size();
        mBuf = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileSize);

        for (int i = 0; i < fileSize; i++)
            System.out.print((char) mBuf.get());

        fileChannel.close();
        fileInputStream.close();
    } catch (IOException exc) {
        System.out.println(exc);
        System.exit(1);
    }
}

From source file:MainClass.java

public static void main(String args[]) {
    FileInputStream fIn;/* w  w w.j a v  a 2s .c om*/
    FileOutputStream fOut;
    FileChannel fIChan, fOChan;
    long fSize;
    MappedByteBuffer mBuf;

    try {
        fIn = new FileInputStream(args[0]);
        fOut = new FileOutputStream(args[1]);

        fIChan = fIn.getChannel();
        fOChan = fOut.getChannel();

        fSize = fIChan.size();

        mBuf = fIChan.map(FileChannel.MapMode.READ_ONLY, 0, fSize);

        fOChan.write(mBuf); // this copies the file

        fIChan.close();
        fIn.close();

        fOChan.close();
        fOut.close();
    } catch (IOException exc) {
        System.out.println(exc);
        System.exit(1);
    } catch (ArrayIndexOutOfBoundsException exc) {
        System.out.println("Usage: Copy from to");
        System.exit(1);
    }
}

From source file:MainClass.java

public static void main(String[] args) throws IOException {

    URL u = new URL("http://www.java2s.com");
    String host = u.getHost();/*from ww  w  .ja v a2 s.  c  o m*/
    int port = 80;
    String file = "/";

    SocketAddress remote = new InetSocketAddress(host, port);
    SocketChannel channel = SocketChannel.open(remote);
    FileOutputStream out = new FileOutputStream("yourfile.htm");
    FileChannel localFile = out.getChannel();

    String request = "GET " + file + " HTTP/1.1\r\n" + "User-Agent: HTTPGrab\r\n" + "Accept: text/*\r\n"
            + "Connection: close\r\n" + "Host: " + host + "\r\n" + "\r\n";

    ByteBuffer header = ByteBuffer.wrap(request.getBytes("US-ASCII"));
    channel.write(header);

    ByteBuffer buffer = ByteBuffer.allocate(8192);
    while (channel.read(buffer) != -1) {
        buffer.flip();
        localFile.write(buffer);
        buffer.clear();
    }

    localFile.close();
    channel.close();
}

From source file:org.commoncrawl.util.S3Downloader.java

public static void main(String[] args) {

    boolean isRequesterPays = args[3].equals("1");
    S3Downloader downloader = new S3Downloader(args[0], args[1], args[2], isRequesterPays);
    String itemToFetch = args[4];

    try {/*  w  ww .j  a  v  a2s  .  co m*/

        downloader.initialize(new Callback() {

            Map<String, FileChannel> channelMap = new HashMap<String, FileChannel>();

            public boolean contentAvailable(int itemId, String itemKey, NIOBufferList contentBuffer) {
                LOG.info("Key:" + itemKey + " GOT:" + contentBuffer.available() + " Bytes");

                FileChannel channel = channelMap.get(itemKey);
                if (channel != null) {
                    try {
                        while (contentBuffer.available() != 0) {
                            ByteBuffer buffer = contentBuffer.read();
                            channel.write(buffer);
                        }
                        return true;
                    } catch (IOException e) {
                        LOG.error(StringUtils.stringifyException(e));
                        return false;
                    }
                }
                return false;
            }

            public void downloadComplete(int itemId, String itemKey) {
                LOG.info("Key:" + itemKey + " DownloadComplete");
                FileChannel channel = channelMap.get(itemKey);
                if (channel != null) {
                    try {
                        channel.close();
                    } catch (IOException e) {
                        LOG.error(StringUtils.stringifyException(e));
                    }
                }
                channelMap.remove(itemKey);
            }

            public void downloadFailed(int itemId, String itemKey, String errorCode) {
                LOG.info("Key:" + itemKey + " DownloadFailed. ErrorCode:" + errorCode);
                FileChannel channel = channelMap.get(itemKey);
                if (channel != null) {
                    try {
                        channel.close();
                    } catch (IOException e) {
                        LOG.error(StringUtils.stringifyException(e));
                    }
                }
                channelMap.remove(itemKey);
            }

            public boolean downloadStarting(int itemId, String itemKey, int contentLength) {
                LOG.info("Key:" + itemKey + " DownloadStarting - ContentLength:" + contentLength);
                File file = new File("/tmp/" + itemKey);
                if (file.exists())
                    file.delete();
                file.getParentFile().mkdirs();
                FileOutputStream fileHandle = null;
                try {
                    fileHandle = new FileOutputStream(file);
                    //LOG.info("Key:" + itemKey + " Created File:" + file.getAbsolutePath());
                    channelMap.put(itemKey, fileHandle.getChannel());
                } catch (IOException e) {
                    LOG.error(StringUtils.stringifyException(e));
                    if (fileHandle != null)
                        try {
                            fileHandle.close();
                        } catch (IOException e1) {
                        }
                    return false;
                }

                return true;
            }
        });

        downloader.fetchItem(itemToFetch);

        downloader.waitForCompletion();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:edu.hawaii.soest.kilonalu.dvp2.DavisWxParser.java

public static void main(String[] args) {

    // Ensure we have a path to the binary file
    if (args.length != 1) {
        logger.info("Please provide the path to a file containing a binary LOOP packet.");
        System.exit(1);/*from w  w  w .j  a v  a2s.  com*/
    } else {
        try {
            // open and read the file
            File packetFile = new File(args[0]);
            FileInputStream fis = new FileInputStream(packetFile);
            FileChannel fileChannel = fis.getChannel();
            ByteBuffer inBuffer = ByteBuffer.allocateDirect(8192);
            ByteBuffer packetBuffer = ByteBuffer.allocateDirect(8192);

            while (fileChannel.read(inBuffer) != -1 || inBuffer.position() > 0) {
                inBuffer.flip();
                packetBuffer.put(inBuffer.get());
                inBuffer.compact();
            }
            fileChannel.close();
            fis.close();
            packetBuffer.put(inBuffer.get());

            // create an instance of the parser, and report the field contents after parsing
            DavisWxParser davisWxParser = new DavisWxParser(packetBuffer);

            // Set up a simple logger that logs to the console
            PropertyConfigurator.configure(davisWxParser.getLogConfigurationFile());

            logger.info("loopID:                         " + davisWxParser.getLoopID());
            logger.info("barTrend:                       " + davisWxParser.getBarTrend());
            logger.info("barTrendAsString:               " + davisWxParser.getBarTrendAsString());
            logger.info("packetType:                     " + davisWxParser.getPacketType());
            logger.info("nextRecord:                     " + davisWxParser.getNextRecord());
            logger.info("barometer:                      " + davisWxParser.getBarometer());
            logger.info("insideTemperature:              " + davisWxParser.getInsideTemperature());
            logger.info("insideHumidity:                 " + davisWxParser.getInsideHumidity());
            logger.info("outsideTemperature:             " + davisWxParser.getOutsideTemperature());
            logger.info("windSpeed:                      " + davisWxParser.getWindSpeed());
            logger.info("tenMinuteAverageWindSpeed:      " + davisWxParser.getTenMinuteAverageWindSpeed());
            logger.info("windDirection:                  " + davisWxParser.getWindDirection());
            logger.info(
                    "extraTemperatures:              " + Arrays.toString(davisWxParser.getExtraTemperatures()));
            logger.info(
                    "soilTemperatures:               " + Arrays.toString(davisWxParser.getSoilTemperatures()));
            logger.info(
                    "leafTemperatures:               " + Arrays.toString(davisWxParser.getLeafTemperatures()));
            logger.info("outsideHumidity:                " + davisWxParser.getOutsideHumidity());
            logger.info(
                    "extraHumidities:                " + Arrays.toString(davisWxParser.getExtraHumidities()));
            logger.info("rainRate:                       " + davisWxParser.getRainRate());
            logger.info("uvRadiation:                    " + davisWxParser.getUvRadiation());
            logger.info("solarRadiation:                 " + davisWxParser.getSolarRadiation());
            logger.info("stormRain:                      " + davisWxParser.getStormRain());
            logger.info("currentStormStartDate:          " + davisWxParser.getCurrentStormStartDate());
            logger.info("dailyRain:                      " + davisWxParser.getDailyRain());
            logger.info("monthlyRain:                    " + davisWxParser.getMonthlyRain());
            logger.info("yearlyRain:                     " + davisWxParser.getYearlyRain());
            logger.info("dailyEvapoTranspiration:        " + davisWxParser.getDailyEvapoTranspiration());
            logger.info("monthlyEvapoTranspiration:      " + davisWxParser.getMonthlyEvapoTranspiration());
            logger.info("yearlyEvapoTranspiration:       " + davisWxParser.getYearlyEvapoTranspiration());
            logger.info("soilMoistures:                  " + Arrays.toString(davisWxParser.getSoilMoistures()));
            logger.info("leafWetnesses:                  " + Arrays.toString(davisWxParser.getLeafWetnesses()));
            logger.info("insideAlarm:                    " + davisWxParser.getInsideAlarm());
            logger.info("rainAlarm:                      " + davisWxParser.getRainAlarm());
            logger.info("outsideAlarms:                  " + davisWxParser.getOutsideAlarms());
            logger.info("extraTemperatureHumidityAlarms: " + davisWxParser.getExtraTemperatureHumidityAlarms());
            logger.info("soilLeafAlarms:                 " + davisWxParser.getSoilLeafAlarms());
            logger.info("transmitterBatteryStatus:       " + davisWxParser.getTransmitterBatteryStatus());
            logger.info("consoleBatteryVoltage:          " + davisWxParser.getConsoleBatteryVoltage());
            logger.info("forecastIconValues:             " + davisWxParser.getForecastAsString());
            logger.info("forecastRuleNumber:             " + davisWxParser.getForecastRuleNumberAsString());
            logger.info("timeOfSunrise:                  " + davisWxParser.getTimeOfSunrise());
            logger.info("timeOfSunset:                   " + davisWxParser.getTimeOfSunset());
            logger.info("recordDelimiter:                " + davisWxParser.getRecordDelimiterAsHexString());
            logger.info("crcChecksum:                    " + davisWxParser.getCrcChecksum());

        } catch (java.io.FileNotFoundException fnfe) {
            fnfe.printStackTrace();

        } catch (java.io.IOException ioe) {
            ioe.printStackTrace();

        }

    }
}

From source file:Main.java

public static void closeFileChannel(FileChannel chl) {
    if (chl != null) {
        try {//from   www .  j  a  v a 2 s  . c o m
            chl.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:Main.java

public static void closeQuietly(FileChannel is) {
    if (is == null)
        return;/*from  w w  w.  j  a va  2 s  . c  o m*/

    try {
        is.close();
    } catch (Exception e) {
    }
}

From source file:Main.java

public static void copyCompletely(InputStream input, OutputStream output) throws IOException {
    // if both are file streams, use channel IO
    if ((output instanceof FileOutputStream) && (input instanceof FileInputStream)) {
        try {//  www.j a v a 2  s  .  c  om
            FileChannel target = ((FileOutputStream) output).getChannel();
            FileChannel source = ((FileInputStream) input).getChannel();

            source.transferTo(0, Integer.MAX_VALUE, target);

            source.close();
            target.close();

            return;
        } catch (Exception e) { /* failover to byte stream version */
        }
    }

    byte[] buf = new byte[8192];
    while (true) {
        int length = input.read(buf);
        if (length < 0)
            break;
        output.write(buf, 0, length);
    }

    try {
        input.close();
    } catch (IOException ignore) {
    }
    try {
        output.close();
    } catch (IOException ignore) {
    }
}

From source file:Main.java

public static ByteBuffer readBytes(String file) throws IOException {
    ByteArrayOutputStream dataOut = new ByteArrayOutputStream();
    FileChannel fChannel = new RandomAccessFile(file, "r").getChannel();
    fChannel.transferTo(0, fChannel.size(), Channels.newChannel(dataOut));
    fChannel.close();
    return ByteBuffer.wrap(dataOut.toByteArray());
}