List of usage examples for java.io FileOutputStream close
public void close() throws IOException
From source file:com.astrientlabs.nyt.NYT.java
public static void main(String[] args) { try {/*ww w. j a va 2 s . c om*/ int session = 112; MembersResponse r = NYT.instance.getMembers(session, NYT.Branch.Senate, null, null); Member[] members = r.getItems(); if (members != null) { String imgUrl; File dir = new File("/Users/rashidmayes/tmp/nyt/", String.valueOf(session)); dir.mkdirs(); File outDir; File outFile; for (Member member : members) { System.out.println(member); imgUrl = NYT.instance.extractImageURL(session, member); System.out.println(imgUrl); if (imgUrl != null) { try { HttpClient httpclient = new DefaultHttpClient(); HttpGet get = new HttpGet(imgUrl); HttpResponse response = httpclient.execute(get); if (response.getStatusLine().getStatusCode() == 200) { outDir = new File(dir, member.getId()); outDir.mkdirs(); outFile = new File(outDir, (member.getFirst_name() + "." + member.getLast_name() + ".jpg") .toLowerCase()); FileOutputStream fos = null; try { fos = new FileOutputStream(outFile); response.getEntity().writeTo(fos); } finally { if (fos != null) { fos.close(); } } } } catch (Exception e) { e.printStackTrace(); } } } } } catch (JsonParseException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.exit(0); }
From source file:com.zarkonnen.longan.Main.java
public static void main(String[] args) throws IOException { // Use Apache Commons CLI (packaged into the Jar) to parse command line options. Options options = new Options(); Option helpO = OptionBuilder.withDescription("print help").create("h"); Option versionO = OptionBuilder.withDescription("print version").create("v"); Option outputO = OptionBuilder.withDescription("output file").withLongOpt("out").hasArg() .withArgName("file").create("o"); Option formatO = OptionBuilder .withDescription("output format: one of plaintext (default) and visualize (debug output in png)") .hasArg().withArgName("format").withLongOpt("format").create(); Option serverO = OptionBuilder.withDescription("launches server mode: Server mode reads " + "command line strings one per line exactly as above. If no output file is " + "specified, returns a line containing the number of output lines before the " + "output. If there is an error, returns a single line with the error message. " + "Shut down server by sending \"quit\".").withLongOpt("server").create(); Option openCLO = OptionBuilder .withDescription(/*from www . j a va 2 s. c om*/ "enables use of the graphics card to " + "support the OCR system. Defaults to true.") .withLongOpt("enable-opencl").hasArg().withArgName("enabled").create(); options.addOption(helpO); options.addOption(versionO); options.addOption(outputO); options.addOption(formatO); options.addOption(serverO); options.addOption(openCLO); CommandLineParser clp = new GnuParser(); try { CommandLine line = clp.parse(options, args); if (line.hasOption("h")) { new HelpFormatter().printHelp(INVOCATION, options); System.exit(0); } if (line.hasOption("v")) { System.out.println(Longan.VERSION); System.exit(0); } boolean enableOpenCL = true; if (line.hasOption("enable-opencl")) { enableOpenCL = line.getOptionValue("enable-opencl").toLowerCase().equals("true") || line.getOptionValue("enable-opencl").equals("1"); } if (line.hasOption("server")) { Longan longan = Longan.getDefaultImplementation(enableOpenCL); BufferedReader inputR = new BufferedReader(new InputStreamReader(System.in)); while (true) { String input = inputR.readLine(); if (input.trim().equals("quit")) { return; } String[] args2 = splitInput(input); Options o2 = new Options(); o2.addOption(outputO); o2.addOption(formatO); try { line = clp.parse(o2, args2); File outFile = null; if (line.hasOption("o")) { outFile = new File(line.getOptionValue("o")); } ResultConverter format = FORMATS.get(line.getOptionValue("format", "plaintext")); if (format != DEFAULT_FORMAT && outFile == null) { System.out.println("You must specify an output file for non-plaintext output."); continue; } if (line.getArgList().isEmpty()) { System.out.println("Please specify an input image."); continue; } if (line.getArgList().size() > 1) { System.err.println("Please specify one input image at a time"); continue; } File inFile = new File((String) line.getArgList().get(0)); if (!inFile.exists()) { System.out.println("The input image does not exist."); continue; } try { Result result = longan.process(ImageIO.read(inFile)); if (outFile == null) { String txt = DEFAULT_FORMAT.convert(result); System.out.println(numNewlines(txt) + 1); System.out.print(txt); } else { if (outFile.getAbsoluteFile().getParentFile() != null && !outFile.getAbsoluteFile().getParentFile().exists()) { outFile.getParentFile().mkdirs(); } FileOutputStream fos = new FileOutputStream(outFile); try { format.write(result, fos); } finally { fos.close(); } } } catch (Exception e) { System.out.println("Processing error: " + exception(e)); } } catch (ParseException e) { System.out.println("Input not recognized: " + exception(e)); } } // End server loop } else { // Single invocation File outFile = null; if (line.hasOption("o")) { outFile = new File(line.getOptionValue("o")); } ResultConverter format = FORMATS.get(line.getOptionValue("format", "plaintext")); if (format != DEFAULT_FORMAT && outFile == null) { System.err.println("You must specify an output file for non-plaintext output."); System.exit(1); } if (line.getArgList().isEmpty()) { System.err.println("Please specify an input image."); new HelpFormatter().printHelp(INVOCATION, options); System.exit(1); } if (line.getArgList().size() > 1) { System.err.println("Please specify one input image only. To process multiple " + "images, use server mode."); System.exit(1); } File inFile = new File((String) line.getArgList().get(0)); if (!inFile.exists()) { System.err.println("The input image does not exist."); System.exit(1); } try { Result result = Longan.getDefaultImplementation(enableOpenCL).process(ImageIO.read(inFile)); if (outFile == null) { String txt = DEFAULT_FORMAT.convert(result); System.out.print(txt); } else { if (outFile.getAbsoluteFile().getParentFile() != null && !outFile.getAbsoluteFile().getParentFile().exists()) { outFile.getParentFile().mkdirs(); } FileOutputStream fos = new FileOutputStream(outFile); try { format.write(format.convert(result), fos); } finally { fos.close(); } } } catch (Exception e) { System.err.println("Processing error: " + exception(e)); System.exit(1); } } } catch (ParseException e) { System.err.println("Parsing command line input failed: " + exception(e)); System.exit(1); } }
From source file:hk.idv.kenson.jrconsole.Console.java
/** * @param args// w w w .j a va2s . c o m */ public static void main(String[] args) { try { Map<String, Object> params = Console.parseArgs(args); if (params.containsKey("help")) { printUsage(); return; } if (params.containsKey("version")) { System.err.println("Version: " + VERSION); return; } if (params.containsKey("debug")) { for (String key : params.keySet()) log.info("\"" + key + "\" => \"" + params.get(key) + "\""); return; } checkParam(params); stepCompile(params); JasperReport jasper = stepLoadReport(params); JasperPrint print = stepFill(jasper, params); InputStream stream = stepExport(print, params); File output = new File(params.get("output").toString()); FileOutputStream fos = new FileOutputStream(output); copy(stream, fos); fos.close(); stream.close(); System.out.println(output.getAbsolutePath()); //Output the report path for pipe } catch (IllegalArgumentException ex) { printUsage(); System.err.println("Error: " + ex.getMessage()); ex.printStackTrace(); } catch (RuntimeException ex) { throw ex; } catch (Exception ex) { throw new RuntimeException("Unexpected exception", ex); } }
From source file:net.cloudkit.relaxation.CaptchaTest.java
public static void main(String[] args) { // System.out.println(Color.WHITE.getRGB()); try {//from w ww .j av a2 s .c o m File fileDirectory = new File("D:\\customs\\"); File[] files = fileDirectory.isDirectory() ? fileDirectory.listFiles() : new File[0]; for (int a = 0; a < files.length; a++) { if (files[a].isDirectory()) continue; InputStream inputStream = new FileInputStream(files[a]); BufferedImage bi = ImageIO.read(inputStream); clearBorder(bi); clearNoise(bi); // List<BufferedImage> subImgs = splitImage(bi); /* for (int i = 0; i < subImgs.size(); i++) { File imageFile = new File("D:\\images\\" + i + ".gif"); ImageIO.write(subImgs.get(i), "gif", imageFile); } */ FileOutputStream fos = new FileOutputStream("D:\\images\\" + files[a].getName().substring(0, files[a].getName().indexOf(".")) + a + ".jpg"); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fos); encoder.encode(bi); fos.close(); // File file2 = new File("D:\\images\\" + a + "_" + files[a].getName()); // ImageIO.write(bi, "gif", file2); } /* CloseableHttpClient httpclient = HttpClients.createDefault(); for (int i = 0; i < 1000; i++) { HttpGet httpGet = new HttpGet("http://query.customs.gov.cn/MNFTQ/Image.aspx?" + Math.random() * 1000); CloseableHttpResponse response1 = httpclient.execute(httpGet); // The underlying HTTP connection is still held by the response object // to allow the response content to be streamed directly from the network socket. // In order to ensure correct deallocation of system resources // the user MUST call CloseableHttpResponse#close() from a finally clause. // Please note that if response content is not fully consumed the underlying // connection cannot be safely re-used and will be shut down and discarded // by the connection manager. try { System.out.println(response1.getStatusLine()); HttpEntity entity1 = response1.getEntity(); // do something useful with the response body // and ensure it is fully consumed InputStream input = entity1.getContent(); File storeFile = new File("D:\\customs\\customs"+ i +".jpg"); FileOutputStream output = new FileOutputStream(storeFile); IOUtils.copy(input, output); output.close(); EntityUtils.consume(entity1); } finally { response1.close(); } } */ } catch (Exception e) { e.printStackTrace(); } }
From source file:net.sf.jsignpdf.verify.Verifier.java
/** * @param args//from w w w. j a va 2 s .co m */ public static void main(String[] args) { // create the Options Option optHelp = new Option("h", "help", false, "print this message"); // Option optVersion = new Option("v", "version", false, // "print version info"); Option optCerts = new Option("c", "cert", true, "use external semicolon separated X.509 certificate files"); optCerts.setArgName("certificates"); Option optPasswd = new Option("p", "password", true, "set password for opening PDF"); optPasswd.setArgName("password"); Option optExtract = new Option("e", "extract", true, "extract signed PDF revisions to given folder"); optExtract.setArgName("folder"); Option optListKs = new Option("lk", "list-keystore-types", false, "list keystore types provided by java"); Option optListCert = new Option("lc", "list-certificates", false, "list certificate aliases in a KeyStore"); Option optKsType = new Option("kt", "keystore-type", true, "use keystore type with given name"); optKsType.setArgName("keystore_type"); Option optKsFile = new Option("kf", "keystore-file", true, "use given keystore file"); optKsFile.setArgName("file"); Option optKsPass = new Option("kp", "keystore-password", true, "password for keystore file (look on -kf option)"); optKsPass.setArgName("password"); Option optFailFast = new Option("ff", "fail-fast", false, "flag which sets the Verifier to exit with error code on the first validation failure"); final Options options = new Options(); options.addOption(optHelp); // options.addOption(optVersion); options.addOption(optCerts); options.addOption(optPasswd); options.addOption(optExtract); options.addOption(optListKs); options.addOption(optListCert); options.addOption(optKsType); options.addOption(optKsFile); options.addOption(optKsPass); options.addOption(optFailFast); CommandLine line = null; try { // create the command line parser CommandLineParser parser = new PosixParser(); // parse the command line arguments line = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Illegal command used: " + exp.getMessage()); System.exit(SignatureVerification.SIG_STAT_CODE_ERROR_UNEXPECTED_PROBLEM); } final boolean failFast = line.hasOption("ff"); final String[] tmpArgs = line.getArgs(); if (line.hasOption("h") || args == null || args.length == 0) { // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(70, "java -jar Verifier.jar [file1.pdf [file2.pdf ...]]", "JSignPdf Verifier is a command line tool for verifying signed PDF documents.", options, null, true); } else if (line.hasOption("lk")) { // list keystores for (String tmpKsType : KeyStoreUtils.getKeyStores()) { System.out.println(tmpKsType); } } else if (line.hasOption("lc")) { // list certificate aliases in the keystore for (String tmpCert : KeyStoreUtils.getCertAliases(line.getOptionValue("kt"), line.getOptionValue("kf"), line.getOptionValue("kp"))) { System.out.println(tmpCert); } } else { final VerifierLogic tmpLogic = new VerifierLogic(line.getOptionValue("kt"), line.getOptionValue("kf"), line.getOptionValue("kp")); tmpLogic.setFailFast(failFast); if (line.hasOption("c")) { String tmpCertFiles = line.getOptionValue("c"); for (String tmpCFile : tmpCertFiles.split(";")) { tmpLogic.addX509CertFile(tmpCFile); } } byte[] tmpPasswd = null; if (line.hasOption("p")) { tmpPasswd = line.getOptionValue("p").getBytes(); } String tmpExtractDir = null; if (line.hasOption("e")) { tmpExtractDir = new File(line.getOptionValue("e")).getPath(); } int exitCode = 0; for (String tmpFilePath : tmpArgs) { int exitCodeForFile = 0; System.out.println("Verifying " + tmpFilePath); final File tmpFile = new File(tmpFilePath); if (!tmpFile.canRead()) { exitCodeForFile = SignatureVerification.SIG_STAT_CODE_ERROR_FILE_NOT_READABLE; System.err.println("Couln't read the file. Check the path and permissions."); if (failFast) { System.exit(exitCodeForFile); } exitCode = Math.max(exitCode, exitCodeForFile); continue; } final VerificationResult tmpResult = tmpLogic.verify(tmpFilePath, tmpPasswd); if (tmpResult.getException() != null) { tmpResult.getException().printStackTrace(); exitCodeForFile = SignatureVerification.SIG_STAT_CODE_ERROR_UNEXPECTED_PROBLEM; if (failFast) { System.exit(exitCodeForFile); } exitCode = Math.max(exitCode, exitCodeForFile); continue; } else { System.out.println("Total revisions: " + tmpResult.getTotalRevisions()); for (SignatureVerification tmpSigVer : tmpResult.getVerifications()) { System.out.println(tmpSigVer.toString()); if (tmpExtractDir != null) { try { File tmpExFile = new File(tmpExtractDir + "/" + tmpFile.getName() + "_" + tmpSigVer.getRevision() + ".pdf"); System.out.println("Extracting to " + tmpExFile.getCanonicalPath()); FileOutputStream tmpFOS = new FileOutputStream(tmpExFile.getCanonicalPath()); InputStream tmpIS = tmpLogic.extractRevision(tmpFilePath, tmpPasswd, tmpSigVer.getName()); IOUtils.copy(tmpIS, tmpFOS); tmpIS.close(); tmpFOS.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } } exitCodeForFile = tmpResult.getVerificationResultCode(); if (failFast && SignatureVerification.isError(exitCodeForFile)) { System.exit(exitCodeForFile); } } exitCode = Math.max(exitCode, exitCodeForFile); } if (exitCode != 0 && tmpArgs.length > 1) { System.exit(SignatureVerification.isError(exitCode) ? SignatureVerification.SIG_STAT_CODE_ERROR_ANY_ERROR : SignatureVerification.SIG_STAT_CODE_WARNING_ANY_WARNING); } else { System.exit(exitCode); } } }
From source file:com.moscona.dataSpace.debug.BadLocks.java
public static void main(String[] args) { try {/*w ww. j a v a2 s . c o m*/ String lockFile = "C:\\Users\\Admin\\projects\\intellitrade\\tmp\\bad.lock"; FileUtils.touch(new File(lockFile)); FileOutputStream stream = new FileOutputStream(lockFile); // FileInputStream stream = new FileInputStream(lockFile); FileChannel channel = stream.getChannel(); // FileLock lock = channel.lock(0,Long.MAX_VALUE, true); FileLock lock = channel.lock(); stream.write(new UndocumentedJava().pid().getBytes()); stream.flush(); long start = System.currentTimeMillis(); // while (System.currentTimeMillis()-start < 10000) { // Thread.sleep(500); // } lock.release(); stream.close(); File f = new File(lockFile); System.out.println("Before write: " + FileUtils.readFileToString(f)); FileUtils.writeStringToFile(f, "written after lock released"); System.out.println("After write: " + FileUtils.readFileToString(f)); } catch (Exception e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } }
From source file:com.ontotext.s4.service.S4ServiceClient.java
public static void main(String... args) { if (args == null || args.length == 0) { printUsageAndTerminate(null);// w ww.ja va2 s .co m } Parameters params = new Parameters(args); String serviceID = params.getValue("service"); if (serviceID == null) { printUsageAndTerminate("No service name provided"); } ServiceDescriptor service = null; try { service = ServicesCatalog.getItem(serviceID); } catch (UnsupportedOperationException uoe) { printUsageAndTerminate("Unsupported service '" + serviceID + '\''); } SupportedMimeType mimetype = SupportedMimeType.PLAINTEXT; if (params.getValue("dtype") != null) { try { mimetype = SupportedMimeType.valueOf(params.getValue("dtype")); } catch (IllegalArgumentException iae) { printUsageAndTerminate("Unsupported document type (dtype) : " + params.getValue("dtype")); } } String inFile = params.getValue("file"); String url = params.getValue("url"); String outFile = params.getValue("out", "result.json"); if (inFile != null) { if (!new File(inFile).exists()) { printUsageAndTerminate("Input file is not found : " + inFile); } } else { if (url == null) { printUsageAndTerminate("Neither input file, nor remote URL provided"); } } Properties creds = readCredentials(params); if (!creds.containsKey("apikey") || !creds.containsKey("secret")) { printUsageAndTerminate("No credentials details found"); } S4ServiceClient client = new S4ServiceClient(service, creds.getProperty("apikey"), creds.getProperty("secret")); try { InputStream resultData = null; if (service.getName().equals("news-classifier")) { resultData = (inFile != null) ? client.classifyFileContentsAsStream(new File(inFile), Charset.forName("UTF-8"), mimetype) : client.classifyDocumentFromUrlAsStream(new URL(url), mimetype); } else { resultData = (inFile != null) ? client.annotateFileContentsAsStream(new File(inFile), Charset.forName("UTF-8"), mimetype, ResponseFormat.JSON) : client.annotateDocumentFromUrlAsStream(new URL(url), mimetype, ResponseFormat.JSON); } FileOutputStream outStream = new FileOutputStream(outFile); IOUtils.copy(resultData, outStream); outStream.close(); resultData.close(); } catch (IOException ioe) { System.out.println(ioe.getMessage()); System.exit(1); } }
From source file:MainClass.java
public static void main(String args[]) throws Exception { FileOutputStream fouts = null; System.setProperty("javax.net.ssl.trustStore", "clienttrust"); SSLSocketFactory ssf = (SSLSocketFactory) SSLSocketFactory.getDefault(); Socket s = ssf.createSocket("127.0.0.1", 5432); OutputStream outs = s.getOutputStream(); PrintStream out = new PrintStream(outs); InputStream ins = s.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(ins)); out.println(args[0]);/*from w w w .ja v a2s .c o m*/ fouts = new FileOutputStream("result.html"); // fouts = new FileOutputStream("result.gif"); int kk; while ((kk = ins.read()) != -1) { fouts.write(kk); } in.close(); fouts.close(); }
From source file:com.run.FtpClientExample.java
public static void main(String[] args) { FTPClient client = new FTPClient(); FileOutputStream fos = null; try {//from ww w . ja v a2s.c om client.connect(ARDroneConstants.IP_ADDRESS, ARDroneConstants.FTP_PORT); if (!client.login("anonymous", "")) System.err.println("login failed"); client.setFileType(FTP.BINARY_FILE_TYPE); String filename = "version.txt"; fos = new FileOutputStream(filename); if (!client.retrieveFile("/" + filename, fos)) System.err.println("cannot find file"); System.out.println("done"); } catch (IOException e) { e.printStackTrace(); } finally { try { if (fos != null) { fos.flush(); fos.close(); } client.disconnect(); } catch (IOException e) { e.printStackTrace(); } } }
From source file:ch.admin.hermes.etl.load.HermesETLApplication.java
/** * Hauptprogramm/*from ww w.j ava 2 s. co m*/ * @param args Commandline Argumente */ public static void main(String[] args) { JFrame frame = null; try { // Crawler fuer Zugriff auf HERMES 5 Online Loesung initialiseren */ crawler = new HermesOnlineCrawler(); // CommandLine Argumente aufbereiten parseCommandLine(args); // Methoden Export (Variante Zuehlke) extrahieren System.out.println("load library " + model); ModelExtract root = new ModelExtract(); root.extract(model); frame = createProgressDialog(); // wird das XML Model von HERMES Online geholt - URL der Templates korrigieren if (scenario != null) { List<Workproduct> workproducts = (List<Workproduct>) root.getObjects().get("workproducts"); for (Workproduct wp : workproducts) for (Template t : wp.getTemplate()) { // Template beinhaltet kompletten URL - keine Aenderung if (t.getUrl().toLowerCase().startsWith("http") || t.getUrl().toLowerCase().startsWith("file")) continue; // Model wird ab Website geholte if (model.startsWith("http")) t.setUrl(crawler.getTemplateURL(scenario, t.getUrl())); // Model ist lokal - Path aus model und relativem Path Template zusammenstellen else { File m = new File(model); t.setUrl(m.getParentFile() + "/" + t.getUrl()); } } } // JavaScript - fuer Import in Fremdsystem if (script.endsWith(".js")) { final JavaScriptEngine js = new JavaScriptEngine(); js.setObjects(root.getObjects()); js.put("progress", progress); js.eval("function log( x ) { println( x ); progress.setString( x ); }"); progress.setString("call main() in " + script); js.put(ScriptEngine.FILENAME, script); js.call(new InputStreamReader(new FileInputStream(script)), "main", new Object[] { site, user, passwd }); } // FreeMarker - fuer Umwandlungen nach HTML else if (script.endsWith(".ftl")) { FileOutputStream out = new FileOutputStream( new File(script.substring(0, script.length() - 3) + "html ")); int i = script.indexOf("templates"); if (i >= 0) script = script.substring(i + "templates".length()); MethodTransform transform = new MethodTransform(); transform.transform(root.getObjects(), script, out); out.close(); } } catch (Exception e) { JOptionPane.showMessageDialog(null, e.toString(), "Fehlerhafte Verarbeitung", JOptionPane.WARNING_MESSAGE); e.printStackTrace(); } if (frame != null) { frame.setVisible(false); frame.dispose(); } System.exit(0); }