Example usage for java.io FileInputStream close

List of usage examples for java.io FileInputStream close

Introduction

In this page you can find the example usage for java.io FileInputStream close.

Prototype

public void close() throws IOException 

Source Link

Document

Closes this file input stream and releases any system resources associated with the stream.

Usage

From source file:edu.umd.cs.marmoset.modelClasses.ZipFileAggregator.java

public static void main(String[] args) throws Exception {
    FileInputStream fis = new FileInputStream("inputfile1.zip");
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    CopyUtils.copy(fis, baos);//ww  w  .j a  v a  2s.c o m

    byte[] byteArr = baos.toByteArray();
    fis.close();

    fis = new FileInputStream("inputfile2.zip");
    baos = new ByteArrayOutputStream();
    CopyUtils.copy(fis, baos);

    byteArr = baos.toByteArray();
    fis.close();

    //      if (args.length < 2) {
    //         System.err.println("Usage: " +
    //               ZipFileAggregator.class.getName() +
    //               " <output file> <file1, file2...>");
    //         System.exit(1);
    //      }
    //
    //      ZipFileAggregator agg=null;
    //      try {
    //         agg=new ZipFileAggregator(new FileOutputStream(args[0]));
    //         for (int i = 1; i < args.length; ++i) {
    //            File inputFile = new File(args[i]);
    //            System.out.println("Adding " + args[i]);
    //            try {
    //               agg.addFile(args[i], inputFile);
    //            } catch (ZipFileAggregator.BadInputZipFileException e) {
    //               System.out.println("Recoverable exception: " + e);
    //               System.out.println("Continuing...");
    //            }
    //         }
    //      } finally {
    //         if (agg != null) agg.close();
    //      }
    //      System.out.println("Done!");
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Socket socket = new Socket("localhost", 8000);
    File file = new File("C:/Users/abc/Desktop/image.jpg");
    FileInputStream fileInputStream = new FileInputStream(file);

    byte[] fileBytes = new byte[(int) file.length()];
    OutputStream outputStream = socket.getOutputStream();
    int content;// w ww  . ja  v a 2 s .c  om
    while ((content = fileInputStream.read(fileBytes)) != -1) {
        outputStream.write(fileBytes, 0, (int) file.length());
    }

    System.out.println("file size is " + fileBytes.length);
    for (byte a : fileBytes) {
        System.out.println(a);
    }
    socket.close();
    fileInputStream.close();
}

From source file:simauthenticator.SimAuthenticator.java

/**
 * @param args the command line arguments
 *//*w  w  w. j a  v a  2  s  . c  o m*/
public static void main(String[] args) throws Exception {

    cliOpts = new Options();
    cliOpts.addOption("U", "url", true, "Connection URL");
    cliOpts.addOption("u", "user", true, "User name");
    cliOpts.addOption("p", "password", true, "User password");
    cliOpts.addOption("d", "domain", true, "Domain name");
    cliOpts.addOption("v", "verbose", false, "Verbose output");
    cliOpts.addOption("k", "keystore", true, "KeyStore path");
    cliOpts.addOption("K", "keystorepass", true, "KeyStore password");
    cliOpts.addOption("h", "help", false, "Print help info");

    CommandLineParser clip = new GnuParser();
    cmd = clip.parse(cliOpts, args);

    if (cmd.hasOption("help")) {
        help();
        return;
    } else {
        boolean valid = init(args);
        if (!valid) {
            return;
        }
    }

    HttpClientContext clientContext = HttpClientContext.create();

    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    char[] keystorePassword = passwk.toCharArray();
    FileInputStream kfis = null;
    try {
        kfis = new FileInputStream(keyStorePath);
        ks.load(kfis, keystorePassword);
    } finally {
        if (kfis != null) {
            kfis.close();
        }
    }

    SSLContext sslContext = SSLContexts.custom().useSSL().loadTrustMaterial(ks).build();
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().setSslcontext(sslContext)
            .setSSLSocketFactory(sslsf).setUserAgent(userAgent);
    ;

    cookieStore = new BasicCookieStore();
    /* BasicClientCookie cookie = new BasicClientCookie("SIM authenticator", "Utility for getting event details");
     cookie.setVersion(0);
     cookie.setDomain(".astelit.ukr");
     cookie.setPath("/");
     cookieStore.addCookie(cookie);*/

    CloseableHttpClient client = httpClientBuilder.build();

    try {

        NTCredentials creds = new NTCredentials(usern, passwu, InetAddress.getLocalHost().getHostName(),
                domain);
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(AuthScope.ANY, creds);
        HttpClientContext context = HttpClientContext.create();
        context.setCredentialsProvider(credsProvider);
        context.setCookieStore(cookieStore);
        HttpGet httpget = new HttpGet(eventUrl);
        if (verbose) {
            System.out.println("executing request " + httpget.getRequestLine());
        }
        HttpResponse response = client.execute(httpget, context);
        HttpEntity entity = response.getEntity();

        HttpPost httppost = new HttpPost(eventUrl);
        List<Cookie> cookies = cookieStore.getCookies();

        if (verbose) {
            System.out.println("----------------------------------------------");
            System.out.println(response.getStatusLine());
            System.out.print("Initial set of cookies: ");
            if (cookies.isEmpty()) {
                System.out.println("none");
            } else {
                for (int i = 0; i < cookies.size(); i++) {
                    System.out.println("- " + cookies.get(i).toString());
                }
            }
        }

        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("usernameInput", usern));
        nvps.add(new BasicNameValuePair("passwordInput", passwu));
        nvps.add(new BasicNameValuePair("domainInput", domain));
        //nvps.add(new BasicNameValuePair("j_username", domain + "\\" + usern));
        //nvps.add(new BasicNameValuePair("j_password", ipAddr + ";" + passwu));
        if (entity != null && verbose) {
            System.out.println("Responce content length: " + entity.getContentLength());

        }

        //System.out.println(EntityUtils.toString(entity));

        httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

        HttpResponse afterPostResponse = client.execute(httppost, context);
        HttpEntity afterPostEntity = afterPostResponse.getEntity();
        cookies = cookieStore.getCookies();
        if (entity != null && verbose) {
            System.out.println("----------------------------------------------");
            System.out.println(afterPostResponse.getStatusLine());
            System.out.println("Responce content length: " + afterPostEntity.getContentLength());
            System.out.print("After POST set of cookies: ");
            if (cookies.isEmpty()) {
                System.out.println("none");
            } else {
                for (int i = 0; i < cookies.size(); i++) {
                    System.out.println("- " + cookies.get(i).toString());
                }
            }
        }

        System.out.println(EntityUtils.toString(afterPostEntity));
        EntityUtils.consume(entity);
        EntityUtils.consume(afterPostEntity);

    } finally {

        client.getConnectionManager().shutdown();
    }

}

From source file:MainClass.java

public static void main(String args[]) {
    FileInputStream fileInputStream;
    FileChannel fileChannel;/*from   w w  w  . jav a  2  s.  c  o  m*/
    long fileSize;
    MappedByteBuffer mBuf;

    try {
        fileInputStream = new FileInputStream("test.txt");
        fileChannel = fileInputStream.getChannel();
        fileSize = fileChannel.size();
        mBuf = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileSize);

        for (int i = 0; i < fileSize; i++)
            System.out.print((char) mBuf.get());

        fileChannel.close();
        fileInputStream.close();
    } catch (IOException exc) {
        System.out.println(exc);
        System.exit(1);
    }
}

From source file:InsertPictureToMySql.java

public static void main(String[] args) throws Exception, IOException, SQLException {
    Class.forName("org.gjt.mm.mysql.Driver");
    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/databaseName", "root", "root");
    String INSERT_PICTURE = "insert into MyPictures(id, name, photo) values (?, ?, ?)";

    FileInputStream fis = null;
    PreparedStatement ps = null;// w ww .ja  v a2s .c  o m
    try {
        conn.setAutoCommit(false);
        File file = new File("myPhoto.png");
        fis = new FileInputStream(file);
        ps = conn.prepareStatement(INSERT_PICTURE);
        ps.setString(1, "001");
        ps.setString(2, "name");
        ps.setBinaryStream(3, fis, (int) file.length());
        ps.executeUpdate();
        conn.commit();
    } finally {
        ps.close();
        fis.close();
    }
}

From source file:Main.java

public static void main(String args[]) throws IOException {
    SequenceInputStream inStream;
    FileInputStream f1 = new FileInputStream("file1.java");
    FileInputStream f2 = new FileInputStream("file2.java");
    inStream = new SequenceInputStream(f1, f2);
    boolean eof = false;
    int byteCount = 0;
    while (!eof) {
        int c = inStream.read();
        if (c == -1)
            eof = true;// ww  w. j a  va2  s.  c  o m
        else {
            System.out.print((char) c);
            ++byteCount;
        }
    }
    System.out.println(byteCount + " bytes were read");
    inStream.close();
    f1.close();
    f2.close();
}

From source file:com.almende.eve.deploy.Boot.java

/**
 * The default agent booter. It takes an EVE yaml file and creates all
 * agents mentioned in the "agents" section.
 * //from  w ww. j ava2 s  .  c  o  m
 * @param args
 *            Single argument: args[0] -> Eve yaml
 */
public static void main(final String[] args) {
    if (args.length == 0) {
        LOG.warning("Missing argument pointing to yaml file:");
        LOG.warning("Usage: java -jar <jarfile> eve.yaml");
        return;
    }
    final ClassLoader cl = new ClassLoader() {
        @Override
        protected Class<?> findClass(final String name) throws ClassNotFoundException {
            Class<?> result = null;
            try {
                result = super.findClass(name);
            } catch (ClassNotFoundException cne) {
            }
            if (result == null) {
                FileInputStream fi = null;
                try {

                    String path = name.replace('.', '/');
                    fi = new FileInputStream(System.getProperty("user.dir") + "/" + path + ".class");
                    byte[] classBytes = new byte[fi.available()];
                    fi.read(classBytes);
                    fi.close();
                    return defineClass(name, classBytes, 0, classBytes.length);
                } catch (Exception e) {
                    LOG.log(Level.WARNING, "Failed to load class:", e);
                }
            }
            if (result == null) {
                throw new ClassNotFoundException(name);
            }
            return result;
        }
    };
    String configFileName = args[0];
    try {
        InputStream is = new FileInputStream(new File(configFileName));
        boot(is, cl);

    } catch (FileNotFoundException e) {
        LOG.log(Level.WARNING, "Couldn't find configfile:" + configFileName, e);
        return;
    }

}

From source file:Main.java

public static void main(String args[]) throws IOException {
    SequenceInputStream inStream;
    FileInputStream f1 = new FileInputStream("ByteArrayIOApp.java");
    FileInputStream f2 = new FileInputStream("FileIOApp.java");
    inStream = new SequenceInputStream(f1, f2);
    boolean eof = false;
    int byteCount = 0;
    while (!eof) {
        int c = inStream.read();
        if (c == -1)
            eof = true;/* ww w.j av  a2  s  . c om*/
        else {
            System.out.print((char) c);
            ++byteCount;
        }
    }
    System.out.println(byteCount + " bytes were read");
    inStream.close();
    f1.close();
    f2.close();
}

From source file:net.itransformers.idiscover.discoverylisteners.TopologyDeviceLogger.java

public static void main(String[] args) throws FileNotFoundException, JAXBException {
    String path = "tmp1";
    File dir = new File(path);
    String[] files = dir.list(new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return (name.startsWith("device") && name.endsWith(".xml"));
        }/*  w  w  w  . j a  v  a  2  s  .  c o  m*/
    });
    TopologyDeviceLogger logger = new TopologyDeviceLogger(path);
    String host = "10.33.0.5";
    String snmpROComm = "public";
    Map<String, String> resourceParams = new HashMap<String, String>();
    resourceParams.put("community", snmpROComm);
    resourceParams.put("version", "1");
    Resource resource = new Resource(host, null, resourceParams);

    for (String fileName : files) {
        FileInputStream is = new FileInputStream(path + File.separator + fileName);
        DiscoveredDeviceData discoveredDeviceData = null;
        try {
            discoveredDeviceData = JaxbMarshalar.unmarshal(DiscoveredDeviceData.class, is);
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        String deviceName = fileName.substring("device-".length(), fileName.length() - ".xml".length());
        logger.handleDevice(deviceName, null, discoveredDeviceData, resource);
    }

}

From source file:MainClass.java

public static void main(String args[]) {
    FileInputStream fIn;
    FileOutputStream fOut;// www .java 2  s  . c  o m
    FileChannel fIChan, fOChan;
    long fSize;
    MappedByteBuffer mBuf;

    try {
        fIn = new FileInputStream(args[0]);
        fOut = new FileOutputStream(args[1]);

        fIChan = fIn.getChannel();
        fOChan = fOut.getChannel();

        fSize = fIChan.size();

        mBuf = fIChan.map(FileChannel.MapMode.READ_ONLY, 0, fSize);

        fOChan.write(mBuf); // this copies the file

        fIChan.close();
        fIn.close();

        fOChan.close();
        fOut.close();
    } catch (IOException exc) {
        System.out.println(exc);
        System.exit(1);
    } catch (ArrayIndexOutOfBoundsException exc) {
        System.out.println("Usage: Copy from to");
        System.exit(1);
    }
}