Example usage for java.io FileInputStream getChannel

List of usage examples for java.io FileInputStream getChannel

Introduction

In this page you can find the example usage for java.io FileInputStream getChannel.

Prototype

public FileChannel getChannel() 

Source Link

Document

Returns the unique java.nio.channels.FileChannel FileChannel object associated with this file input stream.

Usage

From source file:MainClass.java

public static void main(String[] args) {
    File aFile = new File("file.dat");
    FileInputStream inFile = null;

    try {//w  ww . j  a  va  2s . co m
        inFile = new FileInputStream(aFile);
    } catch (FileNotFoundException e) {
        e.printStackTrace(System.err);
        System.exit(0);
    }
    FileChannel inChannel = inFile.getChannel();
    final int COUNT = 6;
    ByteBuffer buf = ByteBuffer.allocate(8 * COUNT);
    long[] data = new long[COUNT];
    try {
        while (inChannel.read(buf) != -1) {
            ((ByteBuffer) (buf.flip())).asLongBuffer().get(data);
            System.out.println();
            for (long prime : data)
                System.out.printf("%10d", prime);
            buf.clear();
        }
        System.out.println("\nEOF reached.");
        inFile.close();
    } catch (IOException e) {
        e.printStackTrace(System.err);
        System.exit(1);
    }
}

From source file:MainClass.java

public static void main(String[] args) {
    File aFile = new File("data.dat");
    FileInputStream inFile = null;

    try {/*from   w  w  w .ja  v a2  s .co  m*/
        inFile = new FileInputStream(aFile);
    } catch (FileNotFoundException e) {
        e.printStackTrace(System.err);
        System.exit(1);
    }

    FileChannel inChannel = inFile.getChannel();
    final int COUNT = 6;
    ByteBuffer buf = ByteBuffer.allocate(8 * COUNT);
    long[] data = new long[COUNT];
    try {
        int pos = 0;
        while (inChannel.read(buf) != -1) {
            try {
                ((ByteBuffer) (buf.flip())).asLongBuffer().get(data);
                pos = data.length;
            } catch (BufferUnderflowException e) {
                LongBuffer longBuf = buf.asLongBuffer();
                pos = longBuf.remaining();
                longBuf.get(data, 0, pos);
            }
            System.out.println();
            for (int i = 0; i < pos; i++) {
                System.out.printf("%10d", data[i]);
            }
            buf.clear();
        }
        System.out.println("\nEOF reached.");
        inFile.close();
    } catch (IOException e) {
        e.printStackTrace(System.err);
        System.exit(1);
    }
}

From source file:MainClass.java

public static void main(String args[]) {
    FileInputStream fIn;
    FileOutputStream fOut;//  w  ww  . ja v  a 2  s  . co m
    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:com.netflix.aegisthus.tools.SSTableExport.java

@SuppressWarnings("rawtypes")
public static void main(String[] args) throws IOException {
    String usage = String.format("Usage: %s <sstable>", SSTableExport.class.getName());

    CommandLineParser parser = new PosixParser();
    try {//from  w w w .  j av  a  2s  .  c om
        cmd = parser.parse(options, args);
    } catch (ParseException e1) {
        System.err.println(e1.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(usage, options);
        System.exit(1);
    }

    if (cmd.getArgs().length != 1) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(usage, options);
        System.exit(1);
    }
    Map<String, AbstractType> convertors = null;
    if (cmd.hasOption(COLUMN_NAME_TYPE)) {
        try {
            convertors = new HashMap<String, AbstractType>();
            convertors.put(SSTableScanner.COLUMN_NAME_KEY,
                    TypeParser.parse(cmd.getOptionValue(COLUMN_NAME_TYPE)));
        } catch (ConfigurationException e) {
            System.err.println(e.getMessage());
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(usage, options);
            System.exit(1);
        } catch (SyntaxException e) {
            System.err.println(e.getMessage());
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(usage, options);
            System.exit(1);
        }
    }
    Descriptor.Version version = null;
    if (cmd.hasOption(OPT_VERSION)) {
        version = new Descriptor.Version(cmd.getOptionValue(OPT_VERSION));
    }

    if (cmd.hasOption(INDEX_SPLIT)) {
        String ssTableFileName;
        DataInput input = null;
        if ("-".equals(cmd.getArgs()[0])) {
            ssTableFileName = System.getProperty("aegisthus.file.name");
            input = new DataInputStream(new BufferedInputStream(System.in, 65536 * 10));
        } else {
            ssTableFileName = new File(cmd.getArgs()[0]).getAbsolutePath();
            input = new DataInputStream(
                    new BufferedInputStream(new FileInputStream(ssTableFileName), 65536 * 10));
        }
        exportIndexSplit(ssTableFileName, input);
    } else if (cmd.hasOption(INDEX)) {
        String ssTableFileName = new File(cmd.getArgs()[0]).getAbsolutePath();
        exportIndex(ssTableFileName);
    } else if (cmd.hasOption(ROWSIZE)) {
        String ssTableFileName = new File(cmd.getArgs()[0]).getAbsolutePath();
        exportRowSize(ssTableFileName);
    } else if ("-".equals(cmd.getArgs()[0])) {
        if (version == null) {
            System.err.println("when streaming must supply file version");
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(usage, options);
            System.exit(1);
        }
        exportStream(version);
    } else {
        String ssTableFileName = new File(cmd.getArgs()[0]).getAbsolutePath();
        FileInputStream fis = new FileInputStream(ssTableFileName);
        InputStream inputStream = new DataInputStream(new BufferedInputStream(fis, 65536 * 10));
        long end = -1;
        if (cmd.hasOption(END)) {
            end = Long.valueOf(cmd.getOptionValue(END));
        }
        if (cmd.hasOption(OPT_COMP)) {
            CompressionMetadata cm = new CompressionMetadata(
                    new BufferedInputStream(new FileInputStream(cmd.getOptionValue(OPT_COMP)), 65536),
                    fis.getChannel().size());
            inputStream = new CompressionInputStream(inputStream, cm);
            end = cm.getDataLength();
        }
        DataInputStream input = new DataInputStream(inputStream);
        if (version == null) {
            version = Descriptor.fromFilename(ssTableFileName).version;
        }
        SSTableScanner scanner = new SSTableScanner(input, convertors, end, version);
        if (cmd.hasOption(OPT_MAX_COLUMN_SIZE)) {
            scanner.setMaxColSize(Long.parseLong(cmd.getOptionValue(OPT_MAX_COLUMN_SIZE)));
        }
        export(scanner);
        if (cmd.hasOption(OPT_MAX_COLUMN_SIZE)) {
            if (scanner.getErrorRowCount() > 0) {
                System.err.println(String.format("%d rows were too large", scanner.getErrorRowCount()));
            }
        }
    }
}

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);//  ww w  .j  a  v a2s  .co m
    } 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 CharSequence fromFile(String filename) throws IOException {
    FileInputStream fis = new FileInputStream(filename);
    FileChannel fc = fis.getChannel();

    // Create a read-only CharBuffer on the file
    ByteBuffer bbuf = fc.map(FileChannel.MapMode.READ_ONLY, 0, (int) fc.size());
    CharBuffer cbuf = Charset.forName("8859_1").newDecoder().decode(bbuf);
    return cbuf;/*from   w ww . ja v a2  s.  c om*/
}

From source file:Main.java

public static String readTxtFromFile(File file) throws Exception {
    ByteBuffer buffer = ByteBuffer.allocate((int) file.length());
    FileInputStream in = new FileInputStream(file);
    in.getChannel().read(buffer);
    in.close();/*  ww  w  .  ja  v a 2 s . co  m*/
    return new String(buffer.array());
}

From source file:thv.th.reader.SpriteElementReader.java

public static SpriteElement readByIndex(FileInputStream is, int index) throws IOException {
    is.getChannel().position(index * 6);

    int tabPos = EndianUtils.readSwappedShort(is);
    int offsetx = is.read();
    int offsety = is.read();
    int layerClass = is.read();
    byte flags = (byte) (0xf & layerClass);
    layerClass = (layerClass & 0xf0) >>> 4;
    int id = is.read();

    return new SpriteElement(index * 6, tabPos, offsetx, offsety, flags, id, layerClass);
}

From source file:Main.java

public static String getFileMD5String(File file) throws IOException {
    FileInputStream in = new FileInputStream(file);
    FileChannel ch = in.getChannel();
    MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
    messagedigest.update(byteBuffer);/*  w  w w  .  j av  a 2 s.  com*/
    return bufferToHex(messagedigest.digest());
}

From source file:Main.java

public static void copyFileFast(FileInputStream is, FileOutputStream os) throws IOException {
    FileChannel in = is.getChannel();
    FileChannel out = os.getChannel();
    in.transferTo(0, in.size(), out);/*from   w ww .j a v  a2 s.  com*/
}