List of usage examples for java.io InputStream close
public void close() throws IOException
From source file:Main.java
public static void main(String[] args) throws Exception { int i;/* w w w .j a va 2s . co m*/ // new input stream created InputStream is = new FileInputStream("C://test.txt"); System.out.println("Characters printed:"); // reads till the end of the stream while ((i = is.read()) != -1) { // converts integer to character char c = (char) i; System.out.print(c); } is.close(); }
From source file:com.music.tools.SongDBDownloader.java
public static void main(String[] args) throws Exception { HttpClient client = new DefaultHttpClient(); // HttpHost proxy = new HttpHost("localhost", 8888); // client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); HttpContext ctx = new BasicHttpContext(); HttpUriRequest req = new HttpGet( "http://www.hooktheory.com/analysis/view/the-beatles/i-want-to-hold-your-hand"); client.execute(req, ctx);/*from www . jav a2s .c o m*/ req.abort(); List<String> urls = getSongUrls( "http://www.hooktheory.com/analysis/browseSearch?sQuery=&sOrderBy=views&nResultsPerPage=525&nPage=1", client, ctx); List<List<? extends NameValuePair>> paramsList = new ArrayList<>(urls.size()); for (String songUrl : urls) { paramsList.addAll(getSongParams(songUrl, client, ctx)); } int i = 0; for (List<? extends NameValuePair> params : paramsList) { HttpPost request = new HttpPost("http://www.hooktheory.com/songs/getXML"); request.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20100101 Firefox/15.0.1"); request.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); request.setHeader("Accept-Encoding", "gzip, deflate"); request.setHeader("Accept-Language", "en,en-us;q=0.7,bg;q=0.3"); request.setHeader("Content-Type", "application/x-www-form-urlencoded"); request.setHeader("Origin", "http://www.hooktheory.com"); request.setHeader("Referer", URLEncoder.encode("http://www.hooktheory.com/swf/DNALive Version 1.0.131.swf", "utf-8")); HttpEntity entity = new UrlEncodedFormEntity(params); request.setEntity(entity); try { HttpResponse response = client.execute(request, ctx); if (response.getStatusLine().getStatusCode() == 200) { InputStream is = response.getEntity().getContent(); String xml = CharStreams.toString(new InputStreamReader(is)); is.close(); Files.write(xml, new File("c:/tmp/musicdb/" + i + ".xml"), Charset.forName("utf-8")); } else { System.out.println(response.getStatusLine()); System.out.println(params); } i++; request.abort(); } catch (Exception ex) { System.out.println(params); ex.printStackTrace(); } } }
From source file:SignatureTest.java
public static void main(String[] args) { try {/*from ww w .jav a 2s .c om*/ if (args[0].equals("-genkeypair")) { KeyPairGenerator pairgen = KeyPairGenerator.getInstance("DSA"); SecureRandom random = new SecureRandom(); pairgen.initialize(KEYSIZE, random); KeyPair keyPair = pairgen.generateKeyPair(); ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(args[1])); out.writeObject(keyPair.getPublic()); out.close(); out = new ObjectOutputStream(new FileOutputStream(args[2])); out.writeObject(keyPair.getPrivate()); out.close(); } else if (args[0].equals("-sign")) { ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[3])); PrivateKey privkey = (PrivateKey) keyIn.readObject(); keyIn.close(); Signature signalg = Signature.getInstance("DSA"); signalg.initSign(privkey); File infile = new File(args[1]); InputStream in = new FileInputStream(infile); int length = (int) infile.length(); byte[] message = new byte[length]; in.read(message, 0, length); in.close(); signalg.update(message); byte[] signature = signalg.sign(); DataOutputStream out = new DataOutputStream(new FileOutputStream(args[2])); int signlength = signature.length; out.writeInt(signlength); out.write(signature, 0, signlength); out.write(message, 0, length); out.close(); } else if (args[0].equals("-verify")) { ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[2])); PublicKey pubkey = (PublicKey) keyIn.readObject(); keyIn.close(); Signature verifyalg = Signature.getInstance("DSA"); verifyalg.initVerify(pubkey); File infile = new File(args[1]); DataInputStream in = new DataInputStream(new FileInputStream(infile)); int signlength = in.readInt(); byte[] signature = new byte[signlength]; in.read(signature, 0, signlength); int length = (int) infile.length() - signlength - 4; byte[] message = new byte[length]; in.read(message, 0, length); in.close(); verifyalg.update(message); if (!verifyalg.verify(signature)) System.out.print("not "); System.out.println("verified"); } } catch (Exception e) { e.printStackTrace(); } }
From source file:com.rest.samples.getImage.java
public static void main(String[] args) { // TODO code application logic here String url = "https://api.adorable.io/avatars/eyes1"; try {/* w ww . j ava 2 s. c om*/ HttpClient hc = HttpClientBuilder.create().build(); HttpGet getMethod = new HttpGet(url); getMethod.addHeader("accept", "application/png"); HttpResponse res = hc.execute(getMethod); if (res.getStatusLine().getStatusCode() != 200) { throw new RuntimeException("Failed : HTTP eror code: " + res.getStatusLine().getStatusCode()); } InputStream is = res.getEntity().getContent(); OutputStream os = new FileOutputStream(new File("img.png")); int read = 0; byte[] bytes = new byte[2048]; while ((read = is.read(bytes)) != -1) { os.write(bytes, 0, read); } is.close(); os.close(); } catch (IOException ex) { Logger.getLogger(SamplesUseHttpclient.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:Main.java
public static void main(String[] args) { try {// w w w . ja v a 2s. c om OutputStream os = new FileOutputStream("test.txt"); InputStream is = new FileInputStream("test.txt"); // write something os.write('A'); // flush the stream os.flush(); // close the stream but it does nothing os.close(); // read what we wrote System.out.println((char) is.read()); is.close(); } catch (Exception ex) { ex.printStackTrace(); } }
From source file:examples.ftp.java
public static final void main(String[] args) { int base = 0; boolean storeFile = false, binaryTransfer = false, error = false; String server, username, password, remote, local; FTPClient ftp;/*ww w .j a va 2 s . c o m*/ for (base = 0; base < args.length; base++) { if (args[base].startsWith("-s")) storeFile = true; else if (args[base].startsWith("-b")) binaryTransfer = true; else break; } if ((args.length - base) != 5) { System.err.println(USAGE); System.exit(1); } server = args[base++]; username = args[base++]; password = args[base++]; remote = args[base++]; local = args[base]; ftp = new FTPClient(); ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out))); try { int reply; ftp.connect(server); System.out.println("Connected to " + server + "."); // After connection attempt, you should check the reply code to verify // success. reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); System.err.println("FTP server refused connection."); System.exit(1); } } catch (IOException e) { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException f) { // do nothing } } System.err.println("Could not connect to server."); e.printStackTrace(); System.exit(1); } __main: try { if (!ftp.login(username, password)) { ftp.logout(); error = true; break __main; } System.out.println("Remote system is " + ftp.getSystemName()); if (binaryTransfer) ftp.setFileType(FTP.BINARY_FILE_TYPE); // Use passive mode as default because most of us are // behind firewalls these days. ftp.enterLocalPassiveMode(); if (storeFile) { InputStream input; input = new FileInputStream(local); ftp.storeFile(remote, input); input.close(); } else { OutputStream output; output = new FileOutputStream(local); ftp.retrieveFile(remote, output); output.close(); } ftp.logout(); } catch (FTPConnectionClosedException e) { error = true; System.err.println("Server closed connection."); e.printStackTrace(); } catch (IOException e) { error = true; e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException f) { // do nothing } } } System.exit(error ? 1 : 0); }
From source file:Main.java
public static void main(String[] args) throws Exception { String WRITE_OBJECT_SQL = "BEGIN " + " INSERT INTO java_objects(object_id, object_name, object_value) " + " VALUES (?, ?, empty_blob()) " + " RETURN object_value INTO ?; " + "END;"; String READ_OBJECT_SQL = "SELECT object_value FROM java_objects WHERE object_id = ?"; Connection conn = getOracleConnection(); conn.setAutoCommit(false);/* www . java 2 s . c o m*/ List<Object> list = new ArrayList<Object>(); list.add("This is a short string."); list.add(new Integer(1234)); list.add(new java.util.Date()); // write object to Oracle long id = 0001; String className = list.getClass().getName(); CallableStatement cstmt = conn.prepareCall(WRITE_OBJECT_SQL); cstmt.setLong(1, id); cstmt.setString(2, className); cstmt.registerOutParameter(3, java.sql.Types.BLOB); cstmt.executeUpdate(); BLOB blob = (BLOB) cstmt.getBlob(3); OutputStream os = blob.getBinaryOutputStream(); ObjectOutputStream oop = new ObjectOutputStream(os); oop.writeObject(list); oop.flush(); oop.close(); os.close(); // Read object from oracle PreparedStatement pstmt = conn.prepareStatement(READ_OBJECT_SQL); pstmt.setLong(1, id); ResultSet rs = pstmt.executeQuery(); rs.next(); InputStream is = rs.getBlob(1).getBinaryStream(); ObjectInputStream oip = new ObjectInputStream(is); Object object = oip.readObject(); className = object.getClass().getName(); oip.close(); is.close(); rs.close(); pstmt.close(); conn.commit(); // de-serialize list a java object from a given objectID List listFromDatabase = (List) object; System.out.println("[After De-Serialization] list=" + listFromDatabase); conn.close(); }
From source file:com.rest.samples.getReportFromJasperServer.java
public static void main(String[] args) { // TODO code application logic here String url = "http://username:password@10.49.28.3:8081/jasperserver/rest_v2/reports/Reportes/vencimientos.pdf?feini=2016-09-30&fefin=2016-09-30"; try {/*from w w w. ja va 2 s.c o m*/ HttpClient hc = HttpClientBuilder.create().build(); HttpGet getMethod = new HttpGet(url); getMethod.addHeader("accept", "application/pdf"); HttpResponse res = hc.execute(getMethod); if (res.getStatusLine().getStatusCode() != 200) { throw new RuntimeException("Failed : HTTP eror code: " + res.getStatusLine().getStatusCode()); } InputStream is = res.getEntity().getContent(); OutputStream os = new FileOutputStream(new File("vencimientos.pdf")); int read = 0; byte[] bytes = new byte[2048]; while ((read = is.read(bytes)) != -1) { os.write(bytes, 0, read); } is.close(); os.close(); if (Desktop.isDesktopSupported()) { File pdfFile = new File("vencimientos.pdf"); Desktop.getDesktop().open(pdfFile); } } catch (IOException ex) { Logger.getLogger(SamplesUseHttpclient.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:PNGDecoder.java
public static void main(String[] args) throws Exception { String name = "logo.png"; if (args.length > 0) name = args[0];//www . ja v a 2 s . c om InputStream in = PNGDecoder.class.getResourceAsStream(name); final BufferedImage image = PNGDecoder.decode(in); in.close(); JFrame f = new JFrame() { public void paint(Graphics g) { Insets insets = getInsets(); g.drawImage(image, insets.left, insets.top, null); } }; f.setVisible(true); Insets insets = f.getInsets(); f.setSize(image.getWidth() + insets.left + insets.right, image.getHeight() + insets.top + insets.bottom); }
From source file:aplicacion.sistema.version.logic.ftp.java
public static final void main(String[] args) { int base = 0; boolean storeFile = false, binaryTransfer = false, error = false; String server, username, password, remote, local; server = "gisbertrepuestos.com.ar"; username = "gisbertrepuestos.com.ar"; password = "ipsilon@1982"; remote = "beta/beta-patch.msp"; local = "c:/beta-patch-from-ftp.msp"; FTPClient ftp;/*from w w w . j av a2s.c om*/ /* for (base = 0; base < args.length; base++) { if (args[base].startsWith("-s")) storeFile = true; else if (args[base].startsWith("-b")) binaryTransfer = true; else break; } if ((args.length - base) != 5) { System.err.println(USAGE); System.exit(1); } server = args[base++]; username = args[base++]; password = args[base++]; remote = args[base++]; local = args[base]; */ ftp = new FTPClient(); ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out))); try { int reply; ftp.connect(server); System.out.println("Connected to " + server + "."); // After connection attempt, you should check the reply code to verify // success. reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); System.err.println("FTP server refused connection."); System.exit(1); } } catch (IOException e) { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException f) { // do nothing } } System.err.println("Could not connect to server."); e.printStackTrace(); System.exit(1); } __main: try { if (!ftp.login(username, password)) { ftp.logout(); error = true; break __main; } System.out.println("Remote system is " + ftp.getSystemName()); if (binaryTransfer) ftp.setFileType(FTP.BINARY_FILE_TYPE); // Use passive mode as default because most of us are // behind firewalls these days. ftp.enterLocalPassiveMode(); if (storeFile) { InputStream input; input = new FileInputStream(local); ftp.storeFile(remote, input); input.close(); } else { OutputStream output; output = new FileOutputStream(local); ftp.retrieveFile(remote, output); output.close(); } ftp.logout(); } catch (FTPConnectionClosedException e) { error = true; System.err.println("Server closed connection."); e.printStackTrace(); } catch (IOException e) { error = true; e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException f) { // do nothing } } } System.exit(error ? 1 : 0); }