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:NewApplication.java

/**
 * @param args the command line arguments
 *///from  ww w.  ja  v a2 s. c o m
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(NewApplication.class.getName()).log(java.util.logging.Level.SEVERE,
                null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(NewApplication.class.getName()).log(java.util.logging.Level.SEVERE,
                null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(NewApplication.class.getName()).log(java.util.logging.Level.SEVERE,
                null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(NewApplication.class.getName()).log(java.util.logging.Level.SEVERE,
                null, ex);
    }
    //</editor-fold>

    Logger log = Logger.getLogger("NewApplication");
    try {
        FileInputStream fis = new FileInputStream("p.properties");
        LogManager.getLogManager().readConfiguration(fis);
        log.setLevel(Level.FINE);
        log.addHandler(new java.util.logging.ConsoleHandler());
        log.setUseParentHandlers(false);

        log.info("starting NewApplication");
        fis.close();
    } catch (Exception e) {
    }
    ;

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new NewApplication().setVisible(true);
        }
    });
}

From source file:com.baidu.rigel.biplatform.ma.file.serv.FileServer.java

/**
 * /*from  w w w  .jav a2 s  .  c o m*/
 * ???server
 * 
 * @param args
 */
public static void main(String[] args) throws Exception {
    //        if (args.length != 1) {
    //            LOGGER.error("can not get enough parameters for starting file server");
    //            printUsage();
    //            System.exit(-1);
    //        }

    FileInputStream fis = null;
    String classLocation = FileServer.class.getProtectionDomain().getCodeSource().getLocation().toString();
    final File configFile = new File(classLocation + "/../conf/fileserver.conf");
    Properties properties = new Properties();
    try {
        if (configFile.exists()) {
            fis = new FileInputStream(configFile);
        } else if (StringUtils.isNotEmpty(args[0])) {
            fis = new FileInputStream(args[0]);
        } else {
            printUsage();
            throw new RuntimeException("can't find correct file server configuration file!");
        }
        properties.load(fis);
    } finally {
        if (fis != null) {
            fis.close();
        }
    }
    int port = -1;
    try {
        port = Integer.valueOf(properties.getProperty(PORT_NUM_KEY));
    } catch (NumberFormatException e) {
        LOGGER.error("parameter is not correct, [port = {}]", args[0]);
        System.exit(-1);
    }

    String location = properties.getProperty(ROOT_DIR_KEY);
    if (StringUtils.isEmpty(location)) {
        LOGGER.error("the location can not be empty");
        System.exit(-1);
    }

    File f = new File(location);
    if (!f.exists() && !f.mkdirs()) {
        LOGGER.error("invalidation location [{}] please verify the input", args[1]);
        System.exit(-1);
    }
    startServer(location, port);
}

From source file:com.mgreau.jboss.as7.cli.CliLauncher.java

public static void main(String[] args) throws Exception {
    int exitCode = 0;
    CommandContext cmdCtx = null;/* w w  w.  ja  va2 s. c o  m*/
    boolean gui = false;
    String appName = "";
    try {
        String argError = null;
        List<String> commands = null;
        File file = null;
        boolean connect = false;
        String defaultControllerProtocol = "http-remoting";
        String defaultControllerHost = null;
        int defaultControllerPort = -1;
        boolean version = false;
        String username = null;
        char[] password = null;
        int connectionTimeout = -1;

        //App deployment
        boolean isAppDeployment = false;
        final Properties props = new Properties();

        for (String arg : args) {
            if (arg.startsWith("--controller=") || arg.startsWith("controller=")) {
                final String fullValue;
                final String value;
                if (arg.startsWith("--")) {
                    fullValue = arg.substring(13);
                } else {
                    fullValue = arg.substring(11);
                }
                final int protocolEnd = fullValue.lastIndexOf("://");
                if (protocolEnd == -1) {
                    value = fullValue;
                } else {
                    value = fullValue.substring(protocolEnd + 3);
                    defaultControllerProtocol = fullValue.substring(0, protocolEnd);
                }

                String portStr = null;
                int colonIndex = value.lastIndexOf(':');
                if (colonIndex < 0) {
                    // default port
                    defaultControllerHost = value;
                } else if (colonIndex == 0) {
                    // default host
                    portStr = value.substring(1);
                } else {
                    final boolean hasPort;
                    int closeBracket = value.lastIndexOf(']');
                    if (closeBracket != -1) {
                        //possible ip v6
                        if (closeBracket > colonIndex) {
                            hasPort = false;
                        } else {
                            hasPort = true;
                        }
                    } else {
                        //probably ip v4
                        hasPort = true;
                    }
                    if (hasPort) {
                        defaultControllerHost = value.substring(0, colonIndex).trim();
                        portStr = value.substring(colonIndex + 1).trim();
                    } else {
                        defaultControllerHost = value;
                    }
                }

                if (portStr != null) {
                    int port = -1;
                    try {
                        port = Integer.parseInt(portStr);
                        if (port < 0) {
                            argError = "The port must be a valid non-negative integer: '" + args + "'";
                        } else {
                            defaultControllerPort = port;
                        }
                    } catch (NumberFormatException e) {
                        argError = "The port must be a valid non-negative integer: '" + arg + "'";
                    }
                }
            } else if ("--connect".equals(arg) || "-c".equals(arg)) {
                connect = true;
            } else if ("--version".equals(arg)) {
                version = true;
            } else if ("--gui".equals(arg)) {
                gui = true;
            } else if (arg.startsWith("--appDeployment=") || arg.startsWith("appDeployment=")) {
                isAppDeployment = true;
                appName = arg.startsWith("--") ? arg.substring(16) : arg.substring(14);
            } else if (arg.startsWith("--file=") || arg.startsWith("file=")) {
                if (file != null) {
                    argError = "Duplicate argument '--file'.";
                    break;
                }
                if (commands != null) {
                    argError = "Only one of '--file', '--commands' or '--command' can appear as the argument at a time.";
                    break;
                }

                final String fileName = arg.startsWith("--") ? arg.substring(7) : arg.substring(5);
                if (!fileName.isEmpty()) {
                    file = new File(fileName);
                    if (!file.exists()) {
                        argError = "File " + file.getAbsolutePath() + " doesn't exist.";
                        break;
                    }
                } else {
                    argError = "Argument '--file' is missing value.";
                    break;
                }
            } else if (arg.startsWith("--commands=") || arg.startsWith("commands=")) {
                if (file != null) {
                    argError = "Only one of '--file', '--commands' or '--command' can appear as the argument at a time.";
                    break;
                }
                if (commands != null) {
                    argError = "Duplicate argument '--command'/'--commands'.";
                    break;
                }
                final String value = arg.startsWith("--") ? arg.substring(11) : arg.substring(9);
                commands = Util.splitCommands(value);
            } else if (arg.startsWith("--command=") || arg.startsWith("command=")) {
                if (file != null) {
                    argError = "Only one of '--file', '--commands' or '--command' can appear as the argument at a time.";
                    break;
                }
                if (commands != null) {
                    argError = "Duplicate argument '--command'/'--commands'.";
                    break;
                }
                final String value = arg.startsWith("--") ? arg.substring(10) : arg.substring(8);
                commands = Collections.singletonList(value);
            } else if (arg.startsWith("--user=")) {
                username = arg.startsWith("--") ? arg.substring(7) : arg.substring(5);
            } else if (arg.startsWith("--password=")) {
                password = (arg.startsWith("--") ? arg.substring(11) : arg.substring(9)).toCharArray();
            } else if (arg.startsWith("--timeout=")) {
                if (connectionTimeout > 0) {
                    argError = "Duplicate argument '--timeout'";
                    break;
                }
                final String value = arg.substring(10);
                try {
                    connectionTimeout = Integer.parseInt(value);
                } catch (final NumberFormatException e) {
                    //
                }
                if (connectionTimeout <= 0) {
                    argError = "The timeout must be a valid positive integer: '" + value + "'";
                }
            } else if (arg.equals("--help") || arg.equals("-h")) {
                commands = Collections.singletonList("help");
            } else if (arg.startsWith("--properties=")) {
                final String value = arg.substring(13);
                final File propertiesFile = new File(value);
                if (!propertiesFile.exists()) {
                    argError = "File doesn't exist: " + propertiesFile.getAbsolutePath();
                    break;
                }

                FileInputStream fis = null;
                try {
                    fis = new FileInputStream(propertiesFile);
                    props.load(fis);
                } catch (FileNotFoundException e) {
                    argError = e.getLocalizedMessage();
                    break;
                } catch (java.io.IOException e) {
                    argError = "Failed to load properties from " + propertiesFile.getAbsolutePath() + ": "
                            + e.getLocalizedMessage();
                    break;
                } finally {
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (java.io.IOException e) {
                        }
                    }
                }
                for (final Object prop : props.keySet()) {
                    AccessController.doPrivileged(new PrivilegedAction<Object>() {
                        public Object run() {
                            System.setProperty((String) prop, (String) props.get(prop));
                            return null;
                        }
                    });
                }
            } else if (!(arg.startsWith("-D") || arg.equals("-XX:"))) {// skip system properties and jvm options
                // assume it's commands
                if (file != null) {
                    argError = "Only one of '--file', '--commands' or '--command' can appear as the argument at a time: "
                            + arg;
                    break;
                }
                if (commands != null) {
                    argError = "Duplicate argument '--command'/'--commands'.";
                    break;
                }
                commands = Util.splitCommands(arg);
            }
        }

        if (argError != null) {
            System.err.println(argError);
            exitCode = 1;
            return;
        }

        if (version) {
            cmdCtx = initCommandContext(defaultControllerProtocol, defaultControllerHost, defaultControllerPort,
                    username, password, false, connect, connectionTimeout);
            VersionHandler.INSTANCE.handle(cmdCtx);
            return;
        }

        if (file != null) {
            cmdCtx = initCommandContext(defaultControllerProtocol, defaultControllerHost, defaultControllerPort,
                    username, password, false, connect, connectionTimeout);
            processFile(file, cmdCtx, isAppDeployment, appName, props);
            return;
        }

        if (commands != null) {
            cmdCtx = initCommandContext(defaultControllerProtocol, defaultControllerHost, defaultControllerPort,
                    username, password, false, connect, connectionTimeout);
            processCommands(commands, cmdCtx);
            return;
        }

        // Interactive mode
        cmdCtx = initCommandContext(defaultControllerProtocol, defaultControllerHost, defaultControllerPort,
                username, password, true, connect, connectionTimeout);
        cmdCtx.interact();
    } catch (Throwable t) {
        t.printStackTrace();
        exitCode = 1;
    } finally {
        if (cmdCtx != null && cmdCtx.getExitCode() != 0) {
            exitCode = cmdCtx.getExitCode();
        }
        if (!gui) {
            System.exit(exitCode);
        }
    }
    System.exit(exitCode);
}

From source file:net.iiit.siel.analysis.lang.LanguageIdentifier.java

/**
 * The main method./*w w  w .jav a2s.  com*/
 *
 * @param args the arguments
 */
public static void main(String args[]) {

    String usage = "Usage: LanguageIdentifier " + "[-identifyrows filename maxlines] "
            + "[-identifyfile charset filename] " + "[-identifyfileset charset files] "
            + "[-identifytext text] " + "[-identifyurl url]";
    int command = 0;

    final int IDFILE = 1;
    final int IDTEXT = 2;
    final int IDURL = 3;
    final int IDFILESET = 4;
    final int IDROWS = 5;

    Vector fileset = new Vector();
    String filename = "";
    String charset = "";
    String url = "";
    String text = "";
    int max = 0;

    // TODO niket writing test args here..
    /*      args = new String[2];
          args[0] = "-identifyurl";
          args[1] = "file:/home1/niket/TamilSamplePage.html";
          //args[2] = "/home1/niket/nutch-clia/input.txt";
    */
    // TODO niket end here

    if (args.length == 0) {
        System.err.println(usage);
        System.exit(-1);
    }

    for (int i = 0; i < args.length; i++) { // parse command line
        if (args[i].equals("-identifyfile")) {
            command = IDFILE;
            charset = args[++i];
            filename = args[++i];
        }

        if (args[i].equals("-identifyurl")) {
            command = IDURL;
            filename = args[++i];
        }

        if (args[i].equals("-identifyrows")) {
            command = IDROWS;
            filename = args[++i];
            max = Integer.parseInt(args[++i]);
        }

        if (args[i].equals("-identifytext")) {
            command = IDTEXT;
            for (i++; i < args.length - 1; i++)
                text += args[i] + " ";
        }

        if (args[i].equals("-identifyfileset")) {
            command = IDFILESET;
            charset = args[++i];
            for (i++; i < args.length; i++) {
                File[] files = null;
                File f = new File(args[i]);
                if (f.isDirectory()) {
                    files = f.listFiles();
                } else {
                    files = new File[] { f };
                }
                for (int j = 0; j < files.length; j++) {
                    fileset.add(files[j].getAbsolutePath());
                }
            }
        }

    }

    Configuration conf = NutchConfiguration.create();
    String lang = null;
    LanguageIdentifier idfr = new LanguageIdentifier(conf);
    File f;
    FileInputStream fis;
    try {
        switch (command) {

        case IDTEXT:
            lang = idfr.identify(text);
            System.out.println("Lang :" + lang);
            break;

        case IDFILE:
            f = new File(filename);
            fis = new FileInputStream(f);
            lang = idfr.identify(fis, charset);
            fis.close();
            break;

        case IDURL:
            lang = LangIdentifierUtility.IdentifyLangFromURLDirectly(filename);

            /*
             * our url identifier is confused or couldn't identify lang from
             * URL
             */
            if (lang == null || lang.equalsIgnoreCase("en")) {
                System.out.println("Ambuguity in identifying language from URL");
            } else {
                System.out.println("Lang was identified(using URL) as: " + lang);
            }
            break;

        case IDROWS:
            f = new File(filename);
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
            String line;
            while (max > 0 && (line = br.readLine()) != null) {
                line = line.trim();
                if (line.length() > 2) {
                    max--;
                    lang = idfr.identify(line);
                    System.out.println("R=" + lang + ":" + line);
                }
            }

            br.close();
            System.exit(0);
            break;

        case IDFILESET:
            /*
             * used for benchs for (int j=128; j<=524288; j*=2) { long start
             * = System.currentTimeMillis(); idfr.analyzeLength = j;
             */
            System.out.println("FILESET");
            Iterator i = fileset.iterator();
            while (i.hasNext()) {
                try {
                    filename = (String) i.next();
                    f = new File(filename);
                    fis = new FileInputStream(f);
                    lang = idfr.identify(fis, charset);
                    fis.close();
                } catch (Exception e) {
                    System.out.println(e);
                }
                System.out.println(filename + " was identified as " + lang);
            }
            /*
             * used for benchs System.out.println(j + "/" +
             * (System.currentTimeMillis()-start)); }
             */
            System.exit(0);
            break;
        }
    } catch (Exception e) {
        System.out.println(e);
        System.out.println("lang could not be identified properly");
        e.printStackTrace();
    }
    System.out.println("text was identified as " + lang);

    /*
     * DONOT delete the next few lines, they should be enabled, when a lang.
     * mapping map needs to be generated. TODO  this is for printing
     * the hashMapRangeLangIDTable only
     * 
     * idfr.langMarkerObject.printHashmapTableWithFormatting();
     * 
     * System.out
     * .println("\n\n\n Printing english text contents in this file:\n");
     * System.out.println(idfr.langMarkerObject.getLangCharacters(
     * LanguageIdentifierConstants.LangShortNames.ENGLISH
     * .langShortName()).toString());
     * 
     * System.out
     * .println("\n\n\n Printing telugu text contents in this file:\n");
     * System.out.println(idfr.langMarkerObject.getLangCharacters(
     * LanguageIdentifierConstants.LangShortNames.TELUGU
     * .langShortName()).toString());
     * 
     * System.out
     * .println("\n\n\n Printing unknown text contents in this file:\n");
     * System.out.println(idfr.langMarkerObject.getLangCharacters(
     * LanguageIdentifierConstants.LangShortNames.UNKNOWN_LANG
     * .langShortName()).toString());
     */
}

From source file:examples.tftp.java

public final static void main(String[] args) {
    boolean receiveFile = true, closed;
    int transferMode = TFTP.BINARY_MODE, argc;
    String arg, hostname, localFilename, remoteFilename;
    TFTPClient tftp;/*from ww  w .  j  av  a2  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 {
                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 {
                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:examples.tftp.java

public final static void main(String[] args) {
    boolean receiveFile = true, closed;
    int transferMode = TFTP.BINARY_MODE, argc;
    String arg, hostname, localFilename, remoteFilename;
    TFTPClient tftp;//www .ja v  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 {
                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 {
                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: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;//from  w w w  .ja va2s . 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: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;//from  w  ww  .  j av  a  2  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:fll.scheduler.TableOptimizer.java

/**
 * @param args//  w w w. j a v a 2  s  .  c om
 */
public static void main(final String[] args) {
    LogUtils.initializeLogging();

    File schedfile = null;
    final Options options = buildOptions();
    try {
        final CommandLineParser parser = new PosixParser();
        final CommandLine cmd = parser.parse(options, args);

        schedfile = new File(cmd.getOptionValue(SCHED_FILE_OPTION));

    } catch (final org.apache.commons.cli.ParseException pe) {
        LOGGER.error(pe.getMessage());
        usage(options);
        System.exit(1);
    }

    FileInputStream fis = null;
    try {
        if (!schedfile.canRead()) {
            LOGGER.fatal(schedfile.getAbsolutePath() + " is not readable");
            System.exit(4);
        }

        final boolean csv = schedfile.getName().endsWith("csv");
        final CellFileReader reader;
        final String sheetName;
        if (csv) {
            reader = new CSVCellReader(schedfile);
            sheetName = null;
        } else {
            sheetName = SchedulerUI.promptForSheetName(schedfile);
            if (null == sheetName) {
                return;
            }
            fis = new FileInputStream(schedfile);
            reader = new ExcelCellReader(fis, sheetName);
        }

        final ColumnInformation columnInfo = TournamentSchedule.findColumns(reader, new LinkedList<String>());
        if (null != fis) {
            fis.close();
            fis = null;
        }

        final List<SubjectiveStation> subjectiveStations = SchedulerUI.gatherSubjectiveStationInformation(null,
                columnInfo);

        // not bothering to get the schedule params as we're just tweaking table
        // assignments, which wont't be effected by the schedule params.
        final SchedParams params = new SchedParams(subjectiveStations, SchedParams.DEFAULT_PERFORMANCE_MINUTES,
                SchedParams.MINIMUM_CHANGETIME_MINUTES, SchedParams.MINIMUM_PERFORMANCE_CHANGETIME_MINUTES);
        final List<String> subjectiveHeaders = new LinkedList<String>();
        for (final SubjectiveStation station : subjectiveStations) {
            subjectiveHeaders.add(station.getName());
        }

        final String name = Utilities.extractBasename(schedfile);

        final TournamentSchedule schedule;
        if (csv) {
            schedule = new TournamentSchedule(name, schedfile, subjectiveHeaders);
        } else {
            fis = new FileInputStream(schedfile);
            schedule = new TournamentSchedule(name, fis, sheetName, subjectiveHeaders);
        }

        final TableOptimizer optimizer = new TableOptimizer(params, schedule,
                schedfile.getAbsoluteFile().getParentFile());
        final long start = System.currentTimeMillis();
        optimizer.optimize(null);
        final long stop = System.currentTimeMillis();
        LOGGER.info("Optimization took: " + (stop - start) / 1000.0 + " seconds");

    } catch (final ParseException e) {
        LOGGER.fatal(e, e);
        System.exit(5);
    } catch (final ScheduleParseException e) {
        LOGGER.fatal(e, e);
        System.exit(6);
    } catch (final IOException e) {
        LOGGER.fatal("Error reading file", e);
        System.exit(4);
    } catch (final RuntimeException e) {
        LOGGER.fatal(e, e);
        throw e;
    } catch (InvalidFormatException e) {
        LOGGER.fatal(e, e);
        System.exit(7);
    } finally {
        try {
            if (null != fis) {
                fis.close();
            }
        } catch (final IOException e) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Error closing stream", e);
            }
        }
    }

}

From source file:io.bfscan.clueweb12.BuildWarcTrecIdMapping.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("bz2 Wikipedia XML dump file")
            .create(INPUT_OPTION));/*from   ww w . j ava 2s. co  m*/
    options.addOption(
            OptionBuilder.withArgName("dir").hasArg().withDescription("index location").create(INDEX_OPTION));
    options.addOption(OptionBuilder.withArgName("num").hasArg()
            .withDescription("maximum number of documents to index").create(MAX_OPTION));
    options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("number of indexing threads")
            .create(THREADS_OPTION));

    options.addOption(new Option(OPTIMIZE_OPTION, "merge indexes into a single segment"));

    CommandLine cmdline = null;
    CommandLineParser parser = new GnuParser();
    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (!cmdline.hasOption(INPUT_OPTION) || !cmdline.hasOption(INDEX_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(BuildWarcTrecIdMapping.class.getCanonicalName(), options);
        System.exit(-1);
    }

    String indexPath = cmdline.getOptionValue(INDEX_OPTION);
    int maxdocs = cmdline.hasOption(MAX_OPTION) ? Integer.parseInt(cmdline.getOptionValue(MAX_OPTION))
            : Integer.MAX_VALUE;
    int threads = cmdline.hasOption(THREADS_OPTION) ? Integer.parseInt(cmdline.getOptionValue(THREADS_OPTION))
            : DEFAULT_NUM_THREADS;

    long startTime = System.currentTimeMillis();

    String path = cmdline.getOptionValue(INPUT_OPTION);
    PrintStream out = new PrintStream(System.out, true, "UTF-8");

    Directory dir = FSDirectory.open(new File(indexPath));
    IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_43, ANALYZER);
    config.setOpenMode(OpenMode.CREATE);

    IndexWriter writer = new IndexWriter(dir, config);
    LOG.info("Creating index at " + indexPath);
    LOG.info("Indexing with " + threads + " threads");

    FileInputStream fis = null;
    BufferedReader br = null;

    try {
        fis = new FileInputStream(new File(path));
        byte[] ignoreBytes = new byte[2];
        fis.read(ignoreBytes); // "B", "Z" bytes from commandline tools
        br = new BufferedReader(new InputStreamReader(new CBZip2InputStream(fis), "UTF8"));

        ExecutorService executor = Executors.newFixedThreadPool(threads);
        int cnt = 0;
        String s;
        while ((s = br.readLine()) != null) {
            Runnable worker = new AddDocumentRunnable(writer, s);
            executor.execute(worker);

            cnt++;
            if (cnt % 1000000 == 0) {
                LOG.info(cnt + " articles added");
            }
            if (cnt >= maxdocs) {
                break;
            }
        }

        executor.shutdown();
        // Wait until all threads are finish
        while (!executor.isTerminated()) {
        }

        LOG.info("Total of " + cnt + " articles indexed.");

        if (cmdline.hasOption(OPTIMIZE_OPTION)) {
            LOG.info("Merging segments...");
            writer.forceMerge(1);
            LOG.info("Done!");
        }

        LOG.info("Total elapsed time: " + (System.currentTimeMillis() - startTime) + "ms");
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        writer.close();
        dir.close();
        out.close();
        br.close();
        fis.close();
    }
}