List of usage examples for java.io DataInputStream close
public void close() throws IOException
From source file:SecurityManagerTest.java
public static void main(String[] args) throws Exception { try {//from w w w . jav a2s .co m System.setSecurityManager(new PasswordSecurityManager("Booga Booga")); } catch (SecurityException se) { System.err.println("SecurityManager already set!"); } DataInputStream in = new DataInputStream(new FileInputStream("inputtext.txt")); DataOutputStream out = new DataOutputStream(new FileOutputStream("outputtext.txt")); String inputString; while ((inputString = in.readLine()) != null) { out.writeBytes(inputString); out.writeByte('\n'); } in.close(); out.close(); }
From source file:createSod.java
/** * @param args/*from w w w. j a va 2 s . com*/ * @throws CMSException */ public static void main(String[] args) throws Exception { try { CommandLine options = verifyArgs(args); String privateKeyLocation = options.getOptionValue("privatekey"); String keyPassword = options.getOptionValue("keypass"); String certificate = options.getOptionValue("certificate"); String sodContent = options.getOptionValue("content"); String sod = ""; if (options.hasOption("out")) { sod = options.getOptionValue("out"); } // CHARGEMENT DU FICHIER PKCS#12 KeyStore ks = null; char[] password = null; Security.addProvider(new BouncyCastleProvider()); try { ks = KeyStore.getInstance("PKCS12"); // Password pour le fichier personnal_nyal.p12 password = keyPassword.toCharArray(); ks.load(new FileInputStream(privateKeyLocation), password); } catch (Exception e) { System.out.println("Erreur: fichier " + privateKeyLocation + " n'est pas un fichier pkcs#12 valide ou passphrase incorrect"); return; } // RECUPERATION DU COUPLE CLE PRIVEE/PUBLIQUE ET DU CERTIFICAT PUBLIQUE X509Certificate cert = null; PrivateKey privatekey = null; PublicKey publickey = null; try { Enumeration en = ks.aliases(); String ALIAS = ""; Vector vectaliases = new Vector(); while (en.hasMoreElements()) vectaliases.add(en.nextElement()); String[] aliases = (String[]) (vectaliases.toArray(new String[0])); for (int i = 0; i < aliases.length; i++) if (ks.isKeyEntry(aliases[i])) { ALIAS = aliases[i]; break; } privatekey = (PrivateKey) ks.getKey(ALIAS, password); cert = (X509Certificate) ks.getCertificate(ALIAS); publickey = ks.getCertificate(ALIAS).getPublicKey(); } catch (Exception e) { e.printStackTrace(); return; } // Chargement du certificat partir du fichier InputStream inStream = new FileInputStream(certificate); CertificateFactory cf = CertificateFactory.getInstance("X.509"); cert = (X509Certificate) cf.generateCertificate(inStream); inStream.close(); // Chargement du fichier qui va tre sign File file_to_sign = new File(sodContent); byte[] buffer = new byte[(int) file_to_sign.length()]; DataInputStream in = new DataInputStream(new FileInputStream(file_to_sign)); in.readFully(buffer); in.close(); // Chargement des certificats qui seront stocks dans le fichier .p7 // Ici, seulement le certificat personnal_nyal.cer sera associ. // Par contre, la chane des certificats non. ArrayList certList = new ArrayList(); certList.add(cert); CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC"); CMSSignedDataGenerator signGen = new CMSSignedDataGenerator(); // privatekey correspond notre cl prive rcupre du fichier PKCS#12 // cert correspond au certificat publique personnal_nyal.cer // Le dernier argument est l'algorithme de hachage qui sera utilis signGen.addSigner(privatekey, cert, CMSSignedDataGenerator.DIGEST_SHA1); signGen.addCertificatesAndCRLs(certs); CMSProcessable content = new CMSProcessableByteArray(buffer); // Generation du fichier CMS/PKCS#7 // L'argument deux permet de signifier si le document doit tre attach avec la signature // Valeur true: le fichier est attach (c'est le cas ici) // Valeur false: le fichier est dtach CMSSignedData signedData = signGen.generate(content, true, "BC"); byte[] signeddata = signedData.getEncoded(); // Ecriture du buffer dans un fichier. if (sod.equals("")) { System.out.print(signeddata.toString()); } else { FileOutputStream envfos = new FileOutputStream(sod); envfos.write(signeddata); envfos.close(); } } catch (OptionException oe) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(NAME, getOptions()); System.exit(-1); } catch (Exception e) { e.printStackTrace(); return; } }
From source file:ReadBinaryFile.java
public static void main(String[] args) throws Exception { NumberFormat cf = NumberFormat.getCurrencyInstance(); File file = new File("product.dat"); DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(file))); boolean eof = false; while (!eof) { Product movie = readMovie(in);/* w w w. j a v a 2 s .co m*/ if (movie == null) eof = true; else { String msg = Integer.toString(movie.year); msg += ": " + movie.title; msg += " (" + cf.format(movie.price) + ")"; System.out.println(msg); } } in.close(); }
From source file:org.apache.nutch.parse.ext.WaxExtParser.java
public static void main(String[] args) throws Exception { if (args.length < 1) { System.out.println("Usage: WaxExtParser PDF_FILE..."); System.exit(1);/*w w w . ja va 2 s. co m*/ } Configuration conf = NutchwaxConfiguration.getConfiguration(); WaxExtParser parser = new WaxExtParser(); parser.setConf(conf); for (int i = 0; i < args.length; i++) { String name = args[i]; String url = "file:" + name; File file = new File(name); byte[] bytes = new byte[(int) file.length()]; DataInputStream in = new DataInputStream(new FileInputStream(file)); try { in.readFully(bytes); Parse parse = parser .getParse(new Content(url, url, bytes, "application/pdf", new Metadata(), conf)); System.out.println(parse.getData().getTitle()); } finally { if (in != null) { in.close(); } } } }
From source file:EOF.java
public static void main(String args[]) { DataInputStream is = null; byte ch;/*from ww w .j ava2 s . c o m*/ try { is = new DataInputStream(new FileInputStream("EOF.java")); while (true) { // exception deals catches EOF ch = is.readByte(); System.out.print((char) ch); System.out.flush(); } } catch (EOFException eof) { System.out.println(" >> Normal program termination."); } catch (FileNotFoundException noFile) { System.err.println("File not found! " + noFile); } catch (IOException io) { System.err.println("I/O error occurred: " + io); } catch (Throwable anything) { System.err.println("Abnormal exception caught !: " + anything); } finally { if (is != null) { try { is.close(); } catch (IOException ignored) { } } } }
From source file:DataIODemo.java
public static void main(String[] args) throws IOException { // write the data out DataOutputStream out = new DataOutputStream(new FileOutputStream("invoice1.txt")); double[] prices = { 19.99, 9.99, 15.99, 3.99, 4.99 }; int[] units = { 12, 8, 13, 29, 50 }; String[] descs = { "Java T-shirt", "Java Mug", "Duke Juggling Dolls", "Java Pin", "Java Key Chain" }; for (int i = 0; i < prices.length; i++) { out.writeDouble(prices[i]);//from ww w . j a v a 2 s . co m out.writeChar('\t'); out.writeInt(units[i]); out.writeChar('\t'); out.writeChars(descs[i]); out.writeChar('\n'); } out.close(); // read it in again DataInputStream in = new DataInputStream(new FileInputStream("invoice1.txt")); double price; int unit; StringBuffer desc; double total = 0.0; try { while (true) { price = in.readDouble(); in.readChar(); // throws out the tab unit = in.readInt(); in.readChar(); // throws out the tab char chr; desc = new StringBuffer(20); char lineSep = System.getProperty("line.separator").charAt(0); while ((chr = in.readChar()) != lineSep) desc.append(chr); System.out.println("You've ordered " + unit + " units of " + desc + " at $" + price); total = total + unit * price; } } catch (EOFException e) { } System.out.println("For a TOTAL of: $" + total); in.close(); }
From source file:edu.stanford.epad.common.pixelmed.SegmentationObjectsFileWriter.java
/** * This demo gets segmentation maps from map_file, then inserts the maps twice as two segments. * //from w w w. j av a 2s . c o m * @param args: java SegmentationObjectsFileWriter dicom_file map_file output_file mode mode is "BINARY" or * "FRACTIONAL". */ public static void main(String[] args) { String input_file = args[0];// "./DicomFiles/CT0010";// String map_file = args[1];// "./TEMP/CT0010.mapbin";// String output_file = args[2];// "./TEMP/CT0010.sobin";//"segmentation_test_out.dcm"; // String mode = args[3]; //"BINARY"; byte[] pixels = null; SegmentationObjectsFileWriter obj = null; short image_width = 0, image_height = 0, image_frames = 0; // Read pixel array from the map_file. File file = new File(map_file); DataInputStream dis = null; pixels = new byte[(int) file.length()]; try { dis = new DataInputStream((new FileInputStream(file))); dis.readFully(pixels); dis.close(); } catch (Exception e1) { e1.printStackTrace(); } finally { IOUtils.closeQuietly(dis); } try { DicomInputStream i_stream = new DicomInputStream(new FileInputStream(input_file)); AttributeList list = new AttributeList(); list.read(i_stream); { // Get sequence format. image_width = (short) Attribute.getSingleIntegerValueOrDefault(list, TagFromName.Columns, 1); image_height = (short) Attribute.getSingleIntegerValueOrDefault(list, TagFromName.Rows, 1); image_frames = (short) Attribute.getSingleIntegerValueOrDefault(list, TagFromName.NumberOfFrames, 1); } short[] orientation = new short[] { 1, 0, 0, 0, 0, 1 }; double[] spacing = new double[] { 0.65, 0.8 }; double thickness = 0.5; AttributeList[] lists = new AttributeList[1]; lists[0] = list; obj = new SegmentationObjectsFileWriter(lists, orientation, spacing, thickness); CodedConcept category = new CodedConcept("C0085089" /* conceptUniqueIdentifier */, "260787004" /* SNOMED CID */, "SRT" /* codingSchemeDesignator */, "SNM3" /* legacyCodingSchemeDesignator */, null /* codingSchemeVersion */, "A-00004" /* codeValue */, "Physical Object" /* codeMeaning */, null /* codeStringEquivalent */, null /* synonynms */); CodedConcept type = new CodedConcept("C0018787" /* conceptUniqueIdentifier */, "80891009" /* SNOMED CID */, "SRT" /* codingSchemeDesignator */, null /* legacyCodingSchemeDesignator */, null /* codingSchemeVersion */, "T-32000" /* codeValue */, "Heart" /* codeMeaning */, null /* codeStringEquivalent */, null /* synonynms */); double[][] positions = new double[image_frames][3]; /* * void AddAllFrames(byte [] frames, int frame_num, int image_width, int image_height, String type, double [][] * positions, short [] patient_orientation, double slice_thickness, double [] pixel_spacing, short stack_id) */ // Segment 1 obj.addOneSegment("Segment No.1 is for ...", category, type); obj.addAllFrames(pixels, image_frames, image_width, image_height, "binary", (short) 0, positions); short stack_id = 2; positions[0][0] = 0.2; obj.addAllFrames(pixels, image_frames, image_width, image_height, "binary", stack_id, positions); // Segment 2 // obj.AddOneSegment(null, null, null); obj.addOneSegment("Segment No.2 is for ...", category, type); obj.addAllFrames(pixels, image_frames, image_width, image_height, "binary", (short) 1, positions); obj.addAllFrames(pixels, image_frames, image_width, image_height, "binary", stack_id, positions); obj.saveDicomFile(output_file); } catch (Exception e) { System.err.println(e); e.printStackTrace(System.err); System.exit(0); } }
From source file:cacheservice.CacheServer.java
/** * @param args the command line arguments *///from w ww .j av a2 s. co m public static void main(String[] args) { // COMUNICACIN CON EL CLIENTE ServerSocket serverSocket; Socket socketCliente; DataInputStream in; //Flujo de datos de entrada DataOutputStream out; //Flujo de datos de salida String mensaje; int laTengoenCache = 0; //COMUNICACIN CON EL INDEX ServerSocket serverSocketIndex; Socket socketIndex; DataOutputStream outIndex; ObjectInputStream inIndex; String mensajeIndex; try { serverSocket = new ServerSocket(4444); System.out.print("SERVIDOR CACHE ACTIVO a la espera de peticiones"); //MIENTRAS PERMANEZCA ACTIVO EL SERVIDOR CACHE ESPERAR? POR PETICIONES DE LOS CLIENTES while (true) { socketCliente = serverSocket.accept(); in = new DataInputStream(socketCliente.getInputStream()); //Entrada de los mensajes del cliente mensaje = in.readUTF(); //Leo el mensaje enviado por el cliente System.out.println("\nHe recibido del cliente: " + mensaje); //Muestro el mensaje recibido por el cliente //int particionBuscada = seleccionarParticion(mensaje, tamanoCache, numeroParticiones); //Busco la particin //double tamanoParticion = Math.ceil( (double)tamanoCache / (double)numeroParticiones); //Thread hilo = new Hilo(mensaje,particionBuscada,cache.GetTable(),(int) tamanoParticion); //hilo.start(); //RESPUESTA DEL SERVIDOR CACHE AL CLIENTE out = new DataOutputStream(socketCliente.getOutputStream()); String respuesta = "Respuesta para " + mensaje; if (laTengoenCache == 1) { out.writeUTF(respuesta); System.out.println("\nTengo la respuesta. He respondido al cliente: " + respuesta); } else { out.writeUTF("miss"); out.close(); in.close(); socketCliente.close(); System.out.println("\nNo tengo la respuesta."); //LEER RESPUESTA DEL SERVIDOR INDEX serverSocketIndex = new ServerSocket(6666); socketIndex = serverSocketIndex.accept(); inIndex = new ObjectInputStream(socketIndex.getInputStream()); JSONObject mensajeRecibidoIndex = (JSONObject) inIndex.readObject(); System.out.println("He recibido del SERVIDOR INDEX: " + mensajeRecibidoIndex); //outIndex.close(); inIndex.close(); socketIndex.close(); } } } catch (Exception e) { System.out.print(e.getMessage()); } }
From source file:Main.java
public static long byteArrayToLong(byte[] input) { try {/*from ww w. j a va 2s . c om*/ ByteArrayInputStream bis = new ByteArrayInputStream(input); DataInputStream dis = new DataInputStream(bis); long numb = dis.readLong(); dis.close(); return numb; } catch (IOException e) { throw new RuntimeException(e); } }
From source file:Main.java
public static byte[] readFileToByteArray(File file) { try {//from w ww.j a v a2s . c o m byte[] fileData = new byte[(int) file.length()]; DataInputStream dis = new DataInputStream(new FileInputStream(file)); dis.readFully(fileData); dis.close(); return fileData; } catch (IOException e) { return null; } }