List of usage examples for java.io FileOutputStream close
public void close() throws IOException
From source file:TFTPExample.java
public static void main(String[] args) { boolean receiveFile = true, closed; int transferMode = TFTP.BINARY_MODE, argc; String arg, hostname, localFilename, remoteFilename; TFTPClient tftp;// ww w .java2 s . c om // Parse options for (argc = 0; argc < args.length; argc++) { arg = args[argc]; if (arg.startsWith("-")) { if (arg.equals("-r")) { receiveFile = true; } else if (arg.equals("-s")) { receiveFile = false; } else if (arg.equals("-a")) { transferMode = TFTP.ASCII_MODE; } else if (arg.equals("-b")) { transferMode = TFTP.BINARY_MODE; } else { System.err.println("Error: unrecognized option."); System.err.print(USAGE); System.exit(1); } } else { break; } } // Make sure there are enough arguments if (args.length - argc != 3) { System.err.println("Error: invalid number of arguments."); System.err.print(USAGE); System.exit(1); } // Get host and file arguments hostname = args[argc]; localFilename = args[argc + 1]; remoteFilename = args[argc + 2]; // Create our TFTP instance to handle the file transfer. tftp = new TFTPClient(); // We want to timeout if a response takes longer than 60 seconds tftp.setDefaultTimeout(60000); // Open local socket try { tftp.open(); } catch (SocketException e) { System.err.println("Error: could not open local UDP socket."); System.err.println(e.getMessage()); System.exit(1); } // We haven't closed the local file yet. closed = false; // If we're receiving a file, receive, otherwise send. if (receiveFile) { FileOutputStream output = null; File file; file = new File(localFilename); // If file exists, don't overwrite it. if (file.exists()) { System.err.println("Error: " + localFilename + " already exists."); System.exit(1); } // Try to open local file for writing try { output = new FileOutputStream(file); } catch (IOException e) { tftp.close(); System.err.println("Error: could not open local file for writing."); System.err.println(e.getMessage()); System.exit(1); } // Try to receive remote file via TFTP try { tftp.receiveFile(remoteFilename, transferMode, output, hostname); } catch (UnknownHostException e) { System.err.println("Error: could not resolve hostname."); System.err.println(e.getMessage()); System.exit(1); } catch (IOException e) { System.err.println("Error: I/O exception occurred while receiving file."); System.err.println(e.getMessage()); System.exit(1); } finally { // Close local socket and output file tftp.close(); try { if (output != null) { output.close(); } closed = true; } catch (IOException e) { closed = false; System.err.println("Error: error closing file."); System.err.println(e.getMessage()); } } if (!closed) { System.exit(1); } } else { // We're sending a file FileInputStream input = null; // Try to open local file for reading try { input = new FileInputStream(localFilename); } catch (IOException e) { tftp.close(); System.err.println("Error: could not open local file for reading."); System.err.println(e.getMessage()); System.exit(1); } // Try to send local file via TFTP try { tftp.sendFile(remoteFilename, transferMode, input, hostname); } catch (UnknownHostException e) { System.err.println("Error: could not resolve hostname."); System.err.println(e.getMessage()); System.exit(1); } catch (IOException e) { System.err.println("Error: I/O exception occurred while sending file."); System.err.println(e.getMessage()); System.exit(1); } finally { // Close local socket and input file tftp.close(); try { if (input != null) { input.close(); } closed = true; } catch (IOException e) { closed = false; System.err.println("Error: error closing file."); System.err.println(e.getMessage()); } } if (!closed) { System.exit(1); } } }
From source file:de.tum.i13.ConvertCsvToProtobuf.java
public static void main(String args[]) { try {//from w w w . jav a 2 s.c o m LineIterator it = FileUtils.lineIterator(new File("/Users/manit/Projects/sdcbenchmark/Dataset/debscsv"), "UTF-8"); FileOutputStream out = new FileOutputStream("/Users/manit/Projects/sdcbenchmark/Dataset/debsprotobuf", true); while (it.hasNext()) { String csvLine = (String) it.next(); byte[] csvLineBytes = csvLine.getBytes(); String line = new String(csvLineBytes, StandardCharsets.UTF_8); Debs2015Protos.Taxitrip.Builder builder = Debs2015Protos.Taxitrip.newBuilder(); String[] splitted = line.split(","); builder.setMedallion(splitted[0]); builder.setHackLicense(splitted[1]); builder.setPickupDatetime(splitted[2]); builder.setDropoffDatetime(splitted[3]); builder.setTripTimeInSecs(Integer.parseInt(splitted[4])); builder.setTripDistance(Float.parseFloat(splitted[5])); builder.setPickupLongitude(Float.parseFloat(splitted[6])); builder.setPickupLatitude(Float.parseFloat(splitted[7])); builder.setDropoffLongitude(Float.parseFloat(splitted[8])); builder.setDropoffLatitude(Float.parseFloat(splitted[9])); builder.setPaymentType(splitted[10]); builder.setFareAmount(Float.parseFloat(splitted[11])); builder.setSurcharge(Float.parseFloat(splitted[12])); builder.setMtaTax(Float.parseFloat(splitted[13])); builder.setTipAmount(Float.parseFloat(splitted[14])); builder.setTollsAmount(Float.parseFloat(splitted[15])); builder.setTotalAmount(Float.parseFloat(splitted[16])); builder.build().writeDelimitedTo(out); } out.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.xiangzhurui.util.ftp.TFTPExample.java
public static void main(String[] args) { boolean receiveFile = true, closed; int transferMode = TFTP.BINARY_MODE, argc; String arg, hostname, localFilename, remoteFilename; TFTPClient tftp;// w w w .jav a 2 s.c o m // Parse options for (argc = 0; argc < args.length; argc++) { arg = args[argc]; if (arg.startsWith("-")) { if (arg.equals("-r")) { receiveFile = true; } else if (arg.equals("-s")) { receiveFile = false; } else if (arg.equals("-a")) { transferMode = TFTP.ASCII_MODE; } else if (arg.equals("-b")) { transferMode = TFTP.BINARY_MODE; } else { System.err.println("Error: unrecognized option."); System.err.print(USAGE); System.exit(1); } } else { break; } } // Make sure there are enough arguments if (args.length - argc != 3) { System.err.println("Error: invalid number of arguments."); System.err.print(USAGE); System.exit(1); } // Get host and file arguments hostname = args[argc]; localFilename = args[argc + 1]; remoteFilename = args[argc + 2]; // Create our TFTP instance to handle the file transfer. tftp = new TFTPClient(); // We want to timeout if a response takes longer than 60 seconds tftp.setDefaultTimeout(60000); // Open local socket try { tftp.open(); } catch (SocketException e) { System.err.println("Error: could not open local UDP socket."); System.err.println(e.getMessage()); System.exit(1); } // We haven't closed the local file yet. closed = false; // If we're receiving a file, receive, otherwise send. if (receiveFile) { FileOutputStream output = null; File file; file = new File(localFilename); // If file exists, don't overwrite it. if (file.exists()) { System.err.println("Error: " + localFilename + " already exists."); System.exit(1); } // Try to open local file for writing try { output = new FileOutputStream(file); } catch (IOException e) { tftp.close(); System.err.println("Error: could not open local file for writing."); System.err.println(e.getMessage()); System.exit(1); } // Try to receive remote file via TFTP try { tftp.receiveFile(remoteFilename, transferMode, output, hostname); } catch (UnknownHostException e) { System.err.println("Error: could not resolve hostname."); System.err.println(e.getMessage()); System.exit(1); } catch (IOException e) { System.err.println("Error: I/O exception occurred while receiving file."); System.err.println(e.getMessage()); System.exit(1); } finally { // Close local socket and output file tftp.close(); try { if (output != null) { output.close(); } closed = true; } catch (IOException e) { closed = false; System.err.println("Error: error closing file."); System.err.println(e.getMessage()); } } if (!closed) { System.exit(1); } } else { // We're sending a file FileInputStream input = null; // Try to open local file for reading try { input = new FileInputStream(localFilename); } catch (IOException e) { tftp.close(); System.err.println("Error: could not open local file for reading."); System.err.println(e.getMessage()); System.exit(1); } // Try to send local file via TFTP try { tftp.sendFile(remoteFilename, transferMode, input, hostname); } catch (UnknownHostException e) { System.err.println("Error: could not resolve hostname."); System.err.println(e.getMessage()); System.exit(1); } catch (IOException e) { System.err.println("Error: I/O exception occurred while sending file."); System.err.println(e.getMessage()); System.exit(1); } finally { // Close local socket and input file tftp.close(); try { if (input != null) { input.close(); } closed = true; } catch (IOException e) { closed = false; System.err.println("Error: error closing file."); System.err.println(e.getMessage()); } } if (!closed) { System.exit(1); } } }
From source file:gov.nasa.ensemble.dictionary.nddl.ParseInterpreter.java
public static void main(String[] args) throws Exception { try {/* ww w . ja v a 2s .c om*/ CommandLineArguments cmd = new CommandLineArguments(args); // Create a resource set to hold the resources. // ResourceSet resourceSet = new ResourceSetImpl(); // Register the package to ensure it is available during loading. // resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap() .put(Resource.Factory.Registry.DEFAULT_EXTENSION, new XMIResourceFactoryImpl()); resourceSet.getPackageRegistry().put(DictionaryPackage.eNS_URI, DictionaryPackage.eINSTANCE); // Construct the URI for the instance file. // The argument is treated as a file path only if it denotes an // existing file. // Otherwise, it's directly treated as a URL. // File file = new File(cmd.getValue(Option.ACTIVITY_DICTIONARY_FILE)); URI uri = file.isFile() ? URI.createFileURI(file.getAbsolutePath()) : URI.createURI(cmd.getValue(Option.ACTIVITY_DICTIONARY_FILE)); try { // Demand load resource for this file. // Resource resource = resourceSet.getResource(uri, true); EActivityDictionary eActivityDictionary = (EActivityDictionary) resource.getContents().get(0); ParseInterpreter parseInterpreter = new ParseInterpreter(eActivityDictionary, cmd.getValue(Option.CPU_STATE), cmd.getValue(Option.CPU_VALUE), cmd.getIntValue(Option.BOOT), cmd.getIntValue(Option.SHUTDOWN), cmd.getIntValue(Option.GAP)); parseInterpreter.interpretAD(false); String path = cmd.getValue(Option.OUTPUT_DIRECTORY_PATH); path = path + uri.trimFileExtension().lastSegment(); FileOutputStream objStream = new FileOutputStream(path + "-objects.nddl"); FileOutputStream modelStream = new FileOutputStream(path + "-model.nddl"); FileOutputStream initStateStream = new FileOutputStream(path + "-initial-state.nddl"); objStream.flush(); modelStream.flush(); initStateStream.flush(); parseInterpreter.writeObjects(objStream); objStream.close(); parseInterpreter.writeCompats(modelStream, path + "-objects.nddl"); modelStream.close(); parseInterpreter.writeInitialState(initStateStream, path + "-model.nddl"); } catch (RuntimeException exception) { System.out.println("Problem loading " + uri); exception.printStackTrace(); } } catch (Exception e) { System.out.println(getManPageText()); } }
From source file:Jpeg.java
public static void main(String args[]) { Image image = null;//from www . j a v a2 s . c o m FileOutputStream dataOut = null; File file, outFile; JpegEncoder jpg; String string = ""; int i, Quality = 80; // Check to see if the input file name has one of the extensions: // .tif, .gif, .jpg // If not, print the standard use info. if (args.length < 2) StandardUsage(); if (!args[0].endsWith(".jpg") && !args[0].endsWith(".tif") && !args[0].endsWith(".gif")) StandardUsage(); // First check to see if there is an OutputFile argument. If there isn't // then name the file "InputFile".jpg // Second check to see if the .jpg extension is on the OutputFile argument. // If there isn't one, add it. // Need to check for the existence of the output file. If it exists already, // rename the file with a # after the file name, then the .jpg extension. if (args.length < 3) { string = args[0].substring(0, args[0].lastIndexOf(".")) + ".jpg"; } else { string = args[2]; if (string.endsWith(".tif") || string.endsWith(".gif")) string = string.substring(0, string.lastIndexOf(".")); if (!string.endsWith(".jpg")) string = string.concat(".jpg"); } outFile = new File(string); i = 1; while (outFile.exists()) { outFile = new File(string.substring(0, string.lastIndexOf(".")) + (i++) + ".jpg"); if (i > 100) System.exit(0); } file = new File(args[0]); if (file.exists()) { try { dataOut = new FileOutputStream(outFile); } catch (IOException e) { } try { Quality = Integer.parseInt(args[1]); } catch (NumberFormatException e) { StandardUsage(); } image = Toolkit.getDefaultToolkit().getImage(args[0]); jpg = new JpegEncoder(image, Quality, dataOut); jpg.Compress(); try { dataOut.close(); } catch (IOException e) { } } else { System.out.println("I couldn't find " + args[0] + ". Is it in another directory?"); } System.exit(0); }
From source file:HttpGet.java
public static void main(String[] args) { SocketChannel server = null; // Channel for reading from server FileOutputStream outputStream = null; // Stream to destination file WritableByteChannel destination; // Channel to write to it try { // Exception handling and channel closing code follows this block // Parse the URL. Note we use the new java.net.URI, not URL here. URI uri = new URI(args[0]); // Now query and verify the various parts of the URI String scheme = uri.getScheme(); if (scheme == null || !scheme.equals("http")) throw new IllegalArgumentException("Must use 'http:' protocol"); String hostname = uri.getHost(); int port = uri.getPort(); if (port == -1) port = 80; // Use default port if none specified String path = uri.getRawPath(); if (path == null || path.length() == 0) path = "/"; String query = uri.getRawQuery(); query = (query == null) ? "" : '?' + query; // Combine the hostname and port into a single address object. // java.net.SocketAddress and InetSocketAddress are new in Java 1.4 SocketAddress serverAddress = new InetSocketAddress(hostname, port); // Open a SocketChannel to the server server = SocketChannel.open(serverAddress); // Put together the HTTP request we'll send to the server. String request = "GET " + path + query + " HTTP/1.1\r\n" + // The request "Host: " + hostname + "\r\n" + // Required in HTTP 1.1 "Connection: close\r\n" + // Don't keep connection open "User-Agent: " + HttpGet.class.getName() + "\r\n" + "\r\n"; // Blank // line // indicates // end of // request // headers // Now wrap a CharBuffer around that request string CharBuffer requestChars = CharBuffer.wrap(request); // Get a Charset object to encode the char buffer into bytes Charset charset = Charset.forName("ISO-8859-1"); // Use the charset to encode the request into a byte buffer ByteBuffer requestBytes = charset.encode(requestChars); // Finally, we can send this HTTP request to the server. server.write(requestBytes);//from w w w . java 2s . com // Set up an output channel to send the output to. if (args.length > 1) { // Use a specified filename outputStream = new FileOutputStream(args[1]); destination = outputStream.getChannel(); } else // Or wrap a channel around standard out destination = Channels.newChannel(System.out); // Allocate a 32 Kilobyte byte buffer for reading the response. // Hopefully we'll get a low-level "direct" buffer ByteBuffer data = ByteBuffer.allocateDirect(32 * 1024); // Have we discarded the HTTP response headers yet? boolean skippedHeaders = false; // The code sent by the server int responseCode = -1; // Now loop, reading data from the server channel and writing it // to the destination channel until the server indicates that it // has no more data. while (server.read(data) != -1) { // Read data, and check for end data.flip(); // Prepare to extract data from buffer // All HTTP reponses begin with a set of HTTP headers, which // we need to discard. The headers end with the string // "\r\n\r\n", or the bytes 13,10,13,10. If we haven't already // skipped them then do so now. if (!skippedHeaders) { // First, though, read the HTTP response code. // Assume that we get the complete first line of the // response when the first read() call returns. Assume also // that the first 9 bytes are the ASCII characters // "HTTP/1.1 ", and that the response code is the ASCII // characters in the following three bytes. if (responseCode == -1) { responseCode = 100 * (data.get(9) - '0') + 10 * (data.get(10) - '0') + 1 * (data.get(11) - '0'); // If there was an error, report it and quit // Note that we do not handle redirect responses. if (responseCode < 200 || responseCode >= 300) { System.err.println("HTTP Error: " + responseCode); System.exit(1); } } // Now skip the rest of the headers. try { for (;;) { if ((data.get() == 13) && (data.get() == 10) && (data.get() == 13) && (data.get() == 10)) { skippedHeaders = true; break; } } } catch (BufferUnderflowException e) { // If we arrive here, it means we reached the end of // the buffer and didn't find the end of the headers. // There is a chance that the last 1, 2, or 3 bytes in // the buffer were the beginning of the \r\n\r\n // sequence, so back up a bit. data.position(data.position() - 3); // Now discard the headers we have read data.compact(); // And go read more data from the server. continue; } } // Write the data out; drain the buffer fully. while (data.hasRemaining()) destination.write(data); // Now that the buffer is drained, put it into fill mode // in preparation for reading more data into it. data.clear(); // data.compact() also works here } } catch (Exception e) { // Report any errors that arise System.err.println(e); System.err.println("Usage: java HttpGet <URL> [<filename>]"); } finally { // Close the channels and output file stream, if needed try { if (server != null && server.isOpen()) server.close(); if (outputStream != null) outputStream.close(); } catch (IOException e) { } } }
From source file:Main.java
public static void writeFile(File f1, byte[] data) throws IOException { FileOutputStream fos = new FileOutputStream(f1); fos.write(data);//from w w w. j av a 2 s . com fos.close(); }
From source file:Main.java
public static byte[] downloadImageFromURL(String strUrl) throws Exception { InputStream in;/* ww w .ja v a 2 s .co m*/ ByteArrayOutputStream out = new ByteArrayOutputStream(); URL url = new URL(strUrl); in = new BufferedInputStream(url.openStream()); byte[] buf = new byte[2048]; int n = 0; while (-1 != (n = in.read(buf))) { out.write(buf, 0, n); } out.close(); in.close(); byte[] response = out.toByteArray(); FileOutputStream fos = new FileOutputStream("/Users/image.jpg"); fos.write(response); fos.close(); return response; }
From source file:Main.java
public static void createFileFromBytes(byte[] bytes, File file) throws IOException { FileOutputStream os = new FileOutputStream(file); os.write(bytes);/* w w w . j a v a 2s. co m*/ os.close(); }
From source file:Main.java
public static void bytesToFile(byte[] content, String filename) throws Exception { FileOutputStream out = new FileOutputStream(filename); out.write(content);/*from w w w .j a v a 2 s . c o m*/ out.close(); }