List of usage examples for java.io FileInputStream close
public void close() throws IOException
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);/* w w w .j av a2 s .c o 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:it.polimi.tower4clouds.rules.batch.BatchTool.java
public static void main(String[] args) { Options options = buildOptions();//from w w w . ja v a 2 s. co m CommandLineParser parser = new BasicParser(); HelpFormatter formatter = new HelpFormatter(); FileInputStream inputFile = null; try { // parse the command line arguments CommandLine cmd = parser.parse(options, args); if (cmd.getOptions().length != 1) { System.err.println("Parsing failed: Reason: one and only one option is required"); formatter.printHelp("qos-models", options); } else if (cmd.hasOption("h")) { formatter.printHelp("qos-models", options); } else if (cmd.hasOption("v")) { String file = cmd.getOptionValue("v"); inputFile = new FileInputStream(file); MonitoringRules rules = XMLHelper.deserialize(inputFile, MonitoringRules.class); RulesValidator validator = new RulesValidator(); Set<Problem> problems = validator.validateAllRules(rules); printResult(problems); } else if (cmd.hasOption("c")) { String file = cmd.getOptionValue("c"); inputFile = new FileInputStream(file); Constraints constraints = XMLHelper.deserialize(inputFile, Constraints.class); QoSValidator validator = new QoSValidator(); Set<Problem> problems = validator.validateAllConstraints(constraints); printResult(problems); } else if (cmd.hasOption("r")) { String file = cmd.getOptionValue("r"); inputFile = new FileInputStream(file); Constraints constraints = XMLHelper.deserialize(inputFile, Constraints.class); MonitoringRuleFactory factory = new MonitoringRuleFactory(); MonitoringRules rules = factory.makeRulesFromQoSConstraints(constraints); XMLHelper.serialize(rules, System.out); } } catch (ParseException e) { System.err.println("Parsing failed. Reason: " + e.getMessage()); formatter.printHelp("qos-models", options); } catch (FileNotFoundException e) { System.err.println("Could not locate input file: " + e.getMessage()); } catch (JAXBException | SAXException e) { System.err.println("Input file could not be parsed: "); e.printStackTrace(); } catch (Exception e) { System.err.println("Unknown error: "); e.printStackTrace(); } finally { if (inputFile != null) { try { inputFile.close(); } catch (IOException e) { } } } }
From source file:me.mast3rplan.phantombot.PhantomBot.java
public static void main(String[] args) throws IOException { /* List of properties that must exist. */ String requiredProperties[] = new String[] { "oauth", "channel", "owner", "user" }; String requiredPropertiesErrorMessage = ""; /* Properties configuration */ Properties startProperties = new Properties(); /* Indicates that the botlogin.txt file should be overwritten/created. */ Boolean changed = false;/*w ww . ja v a 2 s. c om*/ /* Print the user dir */ com.gmt2001.Console.out.println("The working directory is: " + System.getProperty("user.dir")); /* Load up the bot info from the bot login file */ try { if (new File("./botlogin.txt").exists()) { try { FileInputStream inputStream = new FileInputStream("botlogin.txt"); startProperties.load(inputStream); inputStream.close(); if (startProperties.getProperty("debugon", "false").equals("true")) { com.gmt2001.Console.out.println("Debug Mode Enabled via botlogin.txt"); PhantomBot.enableDebugging = true; } if (startProperties.getProperty("debuglog", "false").equals("true")) { com.gmt2001.Console.out.println("Debug Log Only Mode Enabled via botlogin.txt"); PhantomBot.enableDebugging = true; PhantomBot.enableDebuggingLogOnly = true; } if (startProperties.getProperty("reloadscripts", "false").equals("true")) { com.gmt2001.Console.out.println("Enabling Script Reloading"); PhantomBot.reloadScripts = true; } if (startProperties.getProperty("rhinodebugger", "false").equals("true")) { com.gmt2001.Console.out.println("Rhino Debugger will be launched if system supports it."); PhantomBot.enableRhinoDebugger = true; } } catch (IOException ex) { com.gmt2001.Console.err.printStackTrace(ex); } } else { /* Fill in the Properties object with some default values. Note that some values are left * unset to be caught in the upcoming logic to enforce settings. */ startProperties.setProperty("baseport", "25000"); startProperties.setProperty("usehttps", "false"); startProperties.setProperty("webenable", "true"); startProperties.setProperty("msglimit30", "18.75"); startProperties.setProperty("musicenable", "true"); startProperties.setProperty("whisperlimit60", "60.0"); } } catch (Exception ex) { com.gmt2001.Console.err.printStackTrace(ex); } /* Check to see if there's a webOauth set */ if (startProperties.getProperty("webauth") == null) { startProperties.setProperty("webauth", generateWebAuth()); com.gmt2001.Console.debug.println("New webauth key has been generated for botlogin.txt"); changed = true; } /* Check to see if there's a webOAuthRO set */ if (startProperties.getProperty("webauthro") == null) { startProperties.setProperty("webauthro", generateWebAuth()); com.gmt2001.Console.debug.println("New webauth read-only key has been generated for botlogin.txt"); changed = true; } /* Check to see if there's a panelUsername set */ if (startProperties.getProperty("paneluser") == null) { com.gmt2001.Console.debug.println( "No Panel Username, using default value of 'panel' for Control Panel and YouTube Player"); startProperties.setProperty("paneluser", "panel"); changed = true; } /* Check to see if there's a panelPassword set */ if (startProperties.getProperty("panelpassword") == null) { com.gmt2001.Console.debug.println( "No Panel Password, using default value of 'panel' for Control Panel and YouTube Player"); startProperties.setProperty("panelpassword", "panel"); changed = true; } /* Check to see if there's a youtubeOAuth set */ if (startProperties.getProperty("ytauth") == null) { startProperties.setProperty("ytauth", generateWebAuth()); com.gmt2001.Console.debug.println("New YouTube websocket key has been generated for botlogin.txt"); changed = true; } /* Check to see if there's a youtubeOAuthThro set */ if (startProperties.getProperty("ytauthro") == null) { startProperties.setProperty("ytauthro", generateWebAuth()); com.gmt2001.Console.debug .println("New YouTube read-only websocket key has been generated for botlogin.txt"); changed = true; } /* Make a new botlogin with the botName, oauth or channel is not found */ if (startProperties.getProperty("user") == null || startProperties.getProperty("oauth") == null || startProperties.getProperty("channel") == null) { try { com.gmt2001.Console.out.print("\r\n"); com.gmt2001.Console.out.print("Welcome to the PhantomBot setup process!\r\n"); com.gmt2001.Console.out .print("If you have any issues please report them on our forum or Tweet at us!\r\n"); com.gmt2001.Console.out.print("Forum: https://community.phantombot.tv/\r\n"); com.gmt2001.Console.out.print("Twitter: https://twitter.com/phantombotapp/\r\n"); com.gmt2001.Console.out.print("PhantomBot Knowledgebase: https://docs.phantombot.tv/\r\n"); com.gmt2001.Console.out.print("PhantomBot WebPanel: https://docs.phantombot.tv/kb/panel/\r\n"); com.gmt2001.Console.out.print("\r\n"); com.gmt2001.Console.out.print("\r\n"); com.gmt2001.Console.out.print("1. Please enter the bot's Twitch username: "); startProperties.setProperty("user", System.console().readLine().trim()); com.gmt2001.Console.out.print("\r\n"); com.gmt2001.Console.out .print("2. You will now need a OAuth token for the bot to be able to chat.\r\n"); com.gmt2001.Console.out.print( "Please note, this OAuth token needs to be generated while you're logged in into the bot's Twitch account.\r\n"); com.gmt2001.Console.out.print( "If you're not logged in as the bot, please go to https://twitch.tv/ and login as the bot.\r\n"); com.gmt2001.Console.out.print("Get the bot's OAuth token here: https://twitchapps.com/tmi/\r\n"); com.gmt2001.Console.out.print("Please enter the bot's OAuth token: "); startProperties.setProperty("oauth", System.console().readLine().trim()); com.gmt2001.Console.out.print("\r\n"); com.gmt2001.Console.out.print( "3. You will now need your channel OAuth token for the bot to be able to change your title and game.\r\n"); com.gmt2001.Console.out.print( "Please note, this OAuth token needs to be generated while you're logged in into your caster account.\r\n"); com.gmt2001.Console.out.print( "If you're not logged in as the caster, please go to https://twitch.tv/ and login as the caster.\r\n"); com.gmt2001.Console.out.print("Get the your OAuth token here: https://phantombot.tv/oauth/\r\n"); com.gmt2001.Console.out.print("Please enter your OAuth token: "); startProperties.setProperty("apioauth", System.console().readLine().trim()); com.gmt2001.Console.out.print("\r\n"); com.gmt2001.Console.out .print("4. Please enter the name of the Twitch channel the bot should join: "); startProperties.setProperty("channel", System.console().readLine().trim()); com.gmt2001.Console.out.print("\r\n"); com.gmt2001.Console.out.print("5. Please enter a custom username for the web panel: "); startProperties.setProperty("paneluser", System.console().readLine().trim()); com.gmt2001.Console.out.print("\r\n"); com.gmt2001.Console.out.print("6. Please enter a custom password for the web panel: "); startProperties.setProperty("panelpassword", System.console().readLine().trim()); changed = true; newSetup = true; } catch (NullPointerException ex) { com.gmt2001.Console.err.printStackTrace(ex); com.gmt2001.Console.out.println("[ERROR] Failed to setup PhantomBot. Now exiting..."); System.exit(0); } } /* Make sure the oauth has been set correctly */ if (startProperties.getProperty("oauth") != null) { if (!startProperties.getProperty("oauth").startsWith("oauth") && !startProperties.getProperty("oauth").isEmpty()) { startProperties.setProperty("oauth", "oauth:" + startProperties.getProperty("oauth")); changed = true; } } /* Make sure the apiOAuth has been set correctly */ if (startProperties.getProperty("apioauth") != null) { if (!startProperties.getProperty("apioauth").startsWith("oauth") && !startProperties.getProperty("apioauth").isEmpty()) { startProperties.setProperty("apioauth", "oauth:" + startProperties.getProperty("apioauth")); changed = true; } } /* Make sure the channelName does not have a # */ if (startProperties.getProperty("channel").startsWith("#")) { startProperties.setProperty("channel", startProperties.getProperty("channel").substring(1)); changed = true; } else if (startProperties.getProperty("channel").contains(".tv")) { startProperties.setProperty("channel", startProperties.getProperty("channel") .substring(startProperties.getProperty("channel").indexOf(".tv/") + 4).replaceAll("/", "")); changed = true; } /* Check for the owner after the channel check is done. */ if (startProperties.getProperty("owner") == null) { if (startProperties.getProperty("channel") != null) { if (!startProperties.getProperty("channel").isEmpty()) { startProperties.setProperty("owner", startProperties.getProperty("channel")); changed = true; } } } /* Iterate the properties and delete entries for anything that does not have a * value. */ for (String propertyKey : startProperties.stringPropertyNames()) { if (startProperties.getProperty(propertyKey).isEmpty()) { changed = true; startProperties.remove(propertyKey); } } /* * Check for required settings. */ for (String requiredProperty : requiredProperties) { if (startProperties.getProperty(requiredProperty) == null) { requiredPropertiesErrorMessage += requiredProperty + " "; } } if (!requiredPropertiesErrorMessage.isEmpty()) { com.gmt2001.Console.err.println(); com.gmt2001.Console.err.println("Missing Required Properties: " + requiredPropertiesErrorMessage); com.gmt2001.Console.err.println("Exiting PhantomBot"); System.exit(0); } /* Check to see if anything changed */ if (changed) { Properties outputProperties = new Properties() { @Override public synchronized Enumeration<Object> keys() { return Collections.enumeration(new TreeSet<>(super.keySet())); } }; try { try (FileOutputStream outputStream = new FileOutputStream("botlogin.txt")) { outputProperties.putAll(startProperties); outputProperties.store(outputStream, "PhantomBot Configuration File"); } } catch (IOException ex) { com.gmt2001.Console.err.printStackTrace(ex); } } /* Start PhantomBot */ PhantomBot.instance = new PhantomBot(startProperties); }
From source file:cht.Parser.java
public static void main(String[] args) throws IOException { // TODO get from google drive boolean isUnicode = false; boolean isRemoveInputFileOnComplete = false; int rowNum;//from w w w. j av a 2 s . c om int colNum; Gson gson = new GsonBuilder().setPrettyPrinting().create(); Properties prop = new Properties(); try { prop.load(new FileInputStream("config.txt")); } catch (IOException ex) { ex.printStackTrace(); } String inputFilePath = prop.getProperty("inputFile"); String outputDirectory = prop.getProperty("outputDirectory"); System.out.println(outputDirectory); // optional String unicode = prop.getProperty("unicode"); String removeInputFileOnComplete = prop.getProperty("removeInputFileOnComplete"); inputFilePath = inputFilePath.trim(); outputDirectory = outputDirectory.trim(); if (unicode != null) { isUnicode = Boolean.parseBoolean(unicode.trim()); } if (removeInputFileOnComplete != null) { isRemoveInputFileOnComplete = Boolean.parseBoolean(removeInputFileOnComplete.trim()); } Writer out = null; FileInputStream in = null; final String newLine = System.getProperty("line.separator").toString(); final String separator = File.separator; try { in = new FileInputStream(inputFilePath); Workbook workbook = new XSSFWorkbook(in); Sheet sheet = workbook.getSheetAt(0); rowNum = sheet.getLastRowNum() + 1; colNum = sheet.getRow(0).getPhysicalNumberOfCells(); for (int j = 1; j < colNum; ++j) { String outputFilename = sheet.getRow(0).getCell(j).getStringCellValue(); // guess directory int slash = outputFilename.indexOf('/'); if (slash != -1) { // has directory outputFilename = outputFilename.substring(0, slash) + separator + outputFilename.substring(slash + 1); } String outputPath = FilenameUtils.concat(outputDirectory, outputFilename); System.out.println("--Writing " + outputPath); out = new OutputStreamWriter(new FileOutputStream(outputPath), "UTF-8"); TreeMap<String, Object> map = new TreeMap<String, Object>(); for (int i = 1; i < rowNum; i++) { try { String key = sheet.getRow(i).getCell(0).getStringCellValue(); //String value = ""; Cell tmp = sheet.getRow(i).getCell(j); if (tmp != null) { // not empty string! value = sheet.getRow(i).getCell(j).getStringCellValue(); } if (!key.equals("") && !key.startsWith("#") && !key.startsWith(".")) { value = isUnicode ? StringEscapeUtils.escapeJava(value) : value; int firstdot = key.indexOf("."); String keyName, keyAttribute; if (firstdot > 0) {// a.b.c.d keyName = key.substring(0, firstdot); // a keyAttribute = key.substring(firstdot + 1); // b.c.d TreeMap oldhash = null; Object old = null; if (map.get(keyName) != null) { old = map.get(keyName); if (old instanceof TreeMap == false) { System.out.println("different type of key:" + key); continue; } oldhash = (TreeMap) old; } else { oldhash = new TreeMap(); } int firstdot2 = keyAttribute.indexOf("."); String rootName, childName; if (firstdot2 > 0) {// c, d.f --> d, f rootName = keyAttribute.substring(0, firstdot2); childName = keyAttribute.substring(firstdot2 + 1); } else {// c, d -> d, null rootName = keyAttribute; childName = null; } TreeMap<String, Object> object = myPut(oldhash, rootName, childName); map.put(keyName, object); } else {// c, d -> d, null keyName = key; keyAttribute = null; // simple string mode map.put(key, value); } } } catch (Exception e) { // just ingore empty rows } } String json = gson.toJson(map); // output json out.write(json + newLine); out.close(); } in.close(); System.out.println("\n---Complete!---"); System.out.println("Read input file from " + inputFilePath); System.out.println(colNum - 1 + " output files ate generated at " + outputDirectory); System.out.println(rowNum + " records are generated for each output file."); System.out.println("output file is ecoded as unicode? " + (isUnicode ? "yes" : "no")); if (isRemoveInputFileOnComplete) { File input = new File(inputFilePath); input.deleteOnExit(); System.out.println("Deleted " + inputFilePath); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (in != null) { in.close(); } } }
From source file:Main.java
public static byte[] LoadImage(String filePath) throws Exception { File file = new File(filePath); int size = (int) file.length(); byte[] buffer = new byte[size]; FileInputStream in = new FileInputStream(file); in.read(buffer);/*from ww w .ja va2s . com*/ in.close(); return buffer; }
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);//from ww w .j a va2s. c o m in.close(); return new String(buffer.array()); }
From source file:MainClass.java
public static void typeFile(String filename) throws IOException { FileInputStream fin = new FileInputStream(filename); try {// w w w.j a v a2 s . c om copy(fin, System.out); } finally { fin.close(); } }
From source file:Main.java
public static int getFileSize(File file) { int size = 0; try {/* w ww. ja v a 2s. c o m*/ FileInputStream fis = new FileInputStream(file); size = fis.available(); fis.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return size; }
From source file:Main.java
public static Document getXmlDocument(File file) throws Exception { DocumentBuilderFactory docBuilderFactory = null; DocumentBuilder db = null;// w w w . j av a2 s .c o m Document document = null; docBuilderFactory = DocumentBuilderFactory.newInstance(); db = docBuilderFactory.newDocumentBuilder(); if (file.exists()) { FileInputStream in = new FileInputStream(file); document = db.parse(in); in.close(); } db = null; docBuilderFactory = null; return document; }
From source file:Main.java
public static String getStringFromFile(String filePath) throws Exception { FileInputStream fin = new FileInputStream(new File(filePath)); String ret = convertStreamToString(fin); fin.close(); return ret;//from ww w . ja v a2s. c o m }