List of usage examples for java.io File exists
public boolean exists()
From source file:com.act.analysis.surfactant.SurfactantLabeler.java
public static void main(String[] args) throws Exception { Options opts = new Options(); for (Option.Builder b : OPTION_BUILDERS) { opts.addOption(b.build());// ww w. j a v a 2s. c o m } CommandLine cl = null; try { CommandLineParser parser = new DefaultParser(); cl = parser.parse(opts, args); } catch (ParseException e) { System.err.format("Argument parsing failed: %s\n", e.getMessage()); HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } if (cl.hasOption("help")) { HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); return; } File inputFile = new File(cl.getOptionValue(OPTION_INPUT_FILE)); if (!inputFile.isFile()) { System.err.format("No input file at: %s\n", inputFile.getAbsolutePath()); HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } File outputFile = new File(cl.getOptionValue(OPTION_OUTPUT_FILE)); if (outputFile.exists()) { System.err.format("WARNING: output file at %s already exists\n", outputFile.getAbsolutePath()); } /* Sometimes the InChIs might not appear in the input file (like in regression results). Instead a corpus of * names and InChIs can be specified in a separate file and looked up as molecules are read/visualized. The join * field is the key on which the InChI for a given row in the input file is found. */ File inchiSourceFile = null; if (cl.hasOption(OPTION_INCHI_SOURCE)) { inchiSourceFile = new File(cl.getOptionValue(OPTION_INCHI_SOURCE)); boolean err = false; if (!inchiSourceFile.isFile()) { System.err.format("No inchi source file at: %s\n", inchiSourceFile.getAbsolutePath()); err = true; } if (!cl.hasOption(OPTION_INCHI_SOURCE_JOIN_FIELD)) { System.err.format("Must specify a join field when using an inchi source file.\n"); err = true; } if (err) { HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } } SurfactantLabeler surfactantLabeler = new SurfactantLabeler(); surfactantLabeler.runAnalysis(cl.getOptionValue(OPTION_LICENSE_FILE), inputFile, outputFile, inchiSourceFile, cl.getOptionValue(OPTION_INCHI_SOURCE_JOIN_FIELD)); }
From source file:cx2x.Cx2x.java
/** * Main point of entry of the program./*from w w w . ja v a 2 s . c om*/ * * @param args Arguments of the program. * @throws Exception if translation failed. */ public static void main(String[] args) throws Exception { String input; String xcodeMlOutput = null; String fortranOutput = null; String target_option = null; String directive_option = null; String configuration_path = null; String schema_path = null; int maxColumns = 0; boolean forcePure = false; CommandLine cmd; try { cmd = processCommandArgs(args); } catch (ParseException pex) { error(pex.getMessage()); return; } // Help option if (cmd.hasOption("h")) { usage(); return; } // Display target list option if (cmd.hasOption("tl")) { listTarget(); return; } // Display directive list option if (cmd.hasOption("dl")) { listDirectiveLanguage(); return; } // Target option if (cmd.hasOption("t")) { target_option = cmd.getOptionValue("t"); } // Directive option if (cmd.hasOption("dir")) { directive_option = cmd.getOptionValue("dir"); } // Suppressing line directive option if (cmd.hasOption("l")) { XmOption.setIsSuppressLineDirective(true); } // Debug option if (cmd.hasOption("d")) { XmOption.setDebugOutput(true); } // XcodeML/F output file option if (cmd.hasOption("o")) { xcodeMlOutput = cmd.getOptionValue("o"); } // FORTRAN output file option if (cmd.hasOption("f")) { fortranOutput = cmd.getOptionValue("f"); } if (cmd.hasOption("w")) { maxColumns = Integer.parseInt(cmd.getOptionValue("w")); } if (cmd.hasOption("c")) { configuration_path = cmd.getOptionValue("c"); } if (cmd.hasOption("s")) { schema_path = cmd.getOptionValue("s"); } // Check that configuration file exists if (configuration_path == null) { error("Configuration file missing."); return; } File configFile = new File(configuration_path); if (!configFile.exists()) { error("Configuration file not found. " + configuration_path); } if (cmd.hasOption("sc")) { showConfig(configuration_path, schema_path); return; } if (cmd.getArgs().length == 0) { error("no input file"); return; } else { input = cmd.getArgs()[0]; } // Module search path options if (cmd.hasOption("M")) { for (String value : cmd.getOptionValues("M")) { XcodeMLtools_Fmod.addSearchPath(value); } } // Read the configuration file Configuration config; try { config = new Configuration(configuration_path, schema_path); config.setUserDefinedTarget(target_option); config.setUserDefineDirective(directive_option); config.setMaxColumns(maxColumns); } catch (Exception ex) { error(ex.getMessage()); return; } // Force pure option if (cmd.hasOption("fp")) { config.setForcePure(); } // Call the translator to apply transformation on XcodeML/F ClawXcodeMlTranslator translator = new ClawXcodeMlTranslator(input, xcodeMlOutput, config); translator.analyze(); translator.transform(); translator.flush(config); // Produce report if (cmd.hasOption("r")) { ClawTransformationReport report = new ClawTransformationReport(cmd.getOptionValue("r")); report.generate(config, args, translator); } // Decompile XcodeML/F to Fortran FortranDecompiler decompiler = new FortranDecompiler(); if (!decompiler.decompile(fortranOutput, xcodeMlOutput, maxColumns, XmOption.isSuppressLineDirective())) { error("Unable to decompile XcodeML to Fortran"); } }
From source file:org.kuali.student.git.importer.ApplyManualBranchCleanup.java
/** * @param args/*from www . j a v a 2 s .co m*/ */ public static void main(String[] args) { if (args.length < 4 || args.length > 7) { usage(); } File inputFile = new File(args[0]); if (!inputFile.exists()) usage(); boolean bare = false; if (args[2].trim().equals("1")) { bare = true; } String remoteName = args[3].trim(); String refPrefix = Constants.R_HEADS; if (args.length == 5) refPrefix = args[4].trim(); String userName = null; String password = null; if (args.length == 6) userName = args[5].trim(); if (args.length == 7) password = args[6].trim(); try { Repository repo = GitRepositoryUtils.buildFileRepository(new File(args[1]).getAbsoluteFile(), false, bare); Git git = new Git(repo); RevWalk rw = new RevWalk(repo); ObjectInserter objectInserter = repo.newObjectInserter(); BufferedReader fileReader = new BufferedReader(new FileReader(inputFile)); String line = fileReader.readLine(); int lineNumber = 1; BatchRefUpdate batch = repo.getRefDatabase().newBatchUpdate(); List<RefSpec> branchesToDelete = new ArrayList<>(); while (line != null) { if (line.startsWith("#") || line.length() == 0) { // skip over comments and blank lines line = fileReader.readLine(); lineNumber++; continue; } String parts[] = line.trim().split(":"); String branchName = parts[0]; Ref branchRef = repo.getRef(refPrefix + "/" + branchName); if (branchRef == null) { log.warn("line: {}, No branch matching {} exists, skipping.", lineNumber, branchName); line = fileReader.readLine(); lineNumber++; continue; } String tagName = null; if (parts.length > 1) tagName = parts[1]; if (tagName != null) { if (tagName.equals("keep")) { log.info("keeping existing branch for {}", branchName); line = fileReader.readLine(); lineNumber++; continue; } if (tagName.equals("tag")) { /* * Shortcut to say make the tag start with the same name as the branch. */ tagName = branchName; } // create a tag RevCommit commit = rw.parseCommit(branchRef.getObjectId()); ObjectId tag = GitRefUtils.insertTag(tagName, commit, objectInserter); batch.addCommand(new ReceiveCommand(null, tag, Constants.R_TAGS + tagName, Type.CREATE)); log.info("converting branch {} into a tag {}", branchName, tagName); } if (remoteName.equals("local")) { batch.addCommand( new ReceiveCommand(branchRef.getObjectId(), null, branchRef.getName(), Type.DELETE)); } else { // if the branch is remote then remember its name so we can batch delete after we have the full list. branchesToDelete.add(new RefSpec(":" + Constants.R_HEADS + branchName)); } line = fileReader.readLine(); lineNumber++; } fileReader.close(); // run the batch update batch.execute(rw, new TextProgressMonitor()); if (!remoteName.equals("local")) { // push the tag to the remote right now log.info("pushing tags to {}", remoteName); PushCommand pushCommand = git.push().setRemote(remoteName).setPushTags() .setProgressMonitor(new TextProgressMonitor()); if (userName != null) pushCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider(userName, password)); Iterable<PushResult> results = pushCommand.call(); for (PushResult pushResult : results) { if (!pushResult.equals(Result.NEW)) { log.warn("failed to push tag " + pushResult.getMessages()); } } // delete the branches from the remote log.info("pushing branch deletes to remote: {}", remoteName); results = git.push().setRemote(remoteName).setRefSpecs(branchesToDelete) .setProgressMonitor(new TextProgressMonitor()).call(); } objectInserter.release(); rw.release(); } catch (Exception e) { log.error("unexpected Exception ", e); } }
From source file:co.cask.cdap.cli.CLIMain.java
public static void main(String[] args) { final PrintStream output = System.out; Options options = getOptions();/*from www. j a v a2 s. c om*/ CLIMainArgs cliMainArgs = CLIMainArgs.parse(args, options); CommandLineParser parser = new BasicParser(); try { CommandLine command = parser.parse(options, cliMainArgs.getOptionTokens()); if (command.hasOption(HELP_OPTION.getOpt())) { usage(); System.exit(0); } LaunchOptions launchOptions = LaunchOptions.builder() .setUri(command.getOptionValue(URI_OPTION.getOpt(), getDefaultURI().toString())) .setDebug(command.hasOption(DEBUG_OPTION.getOpt())) .setVerifySSL(parseBooleanOption(command, VERIFY_SSL_OPTION, DEFAULT_VERIFY_SSL)) .setAutoconnect(parseBooleanOption(command, AUTOCONNECT_OPTION, DEFAULT_AUTOCONNECT)).build(); String scriptFile = command.getOptionValue(SCRIPT_OPTION.getOpt(), ""); boolean hasScriptFile = command.hasOption(SCRIPT_OPTION.getOpt()); String[] commandArgs = cliMainArgs.getCommandTokens(); try { ClientConfig clientConfig = ClientConfig.builder().setConnectionConfig(null).build(); final CLIConfig cliConfig = new CLIConfig(clientConfig, output, new AltStyleTableRenderer()); CLIMain cliMain = new CLIMain(launchOptions, cliConfig); CLI cli = cliMain.getCLI(); cliMain.tryAutoconnect(); CLIConnectionConfig connectionConfig = new CLIConnectionConfig( cliConfig.getClientConfig().getConnectionConfig(), Id.Namespace.DEFAULT, null); cliMain.updateCLIPrompt(connectionConfig); if (hasScriptFile) { File script = cliMain.getFilePathResolver().resolvePathToFile(scriptFile); if (!script.exists()) { output.println("ERROR: Script file '" + script.getAbsolutePath() + "' does not exist"); System.exit(1); } List<String> scriptLines = Files.readLines(script, Charsets.UTF_8); for (String scriptLine : scriptLines) { output.print(cliMain.getPrompt(connectionConfig)); output.println(scriptLine); cli.execute(scriptLine, output); output.println(); } } else if (commandArgs.length == 0) { cli.startInteractiveMode(output); } else { cli.execute(Joiner.on(" ").join(commandArgs), output); } } catch (Exception e) { e.printStackTrace(output); } } catch (ParseException e) { output.println(e.getMessage()); usage(); } }
From source file:it.isislab.dmason.util.SystemManagement.Worker.thrower.DMasonWorker.java
public static void main(String[] args) { RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean(); //// w ww .j av a 2s .c o m // Get name representing the running Java virtual machine. // It returns something like 6460@AURORA. Where the value // before the @ symbol is the PID. // String jvmName = bean.getName(); //Used for log4j properties System.setProperty("logfile.name", "worker" + jvmName); //Used for log4j properties System.setProperty("steplog.name", "workerStep" + jvmName); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH_mm_ss_SS"); Date date = new Date(); dateFormat.format(date); System.setProperty("timestamp", date.toLocaleString()); System.setProperty("paramsfile.name", "params"); try { File logPath = new File("Logs/workers"); if (logPath.exists()) FileUtils.cleanDirectory(logPath); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } logger = Logger.getLogger(DMasonWorker.class.getCanonicalName()); logger.debug("StartWorker " + version); autoStart = false; connect = false; ip = null; port = null; String topic = ""; updated = false; isBatch = false; topicPrefix = ""; if (args.length == 0) { // Force waiting for beacon (requires ActiveMQWrapper) autoStart = false; connect = true; } else if (args.length == 2) { // Launched with IP and Port ip = args[0]; port = args[1]; autoStart = true; connect = true; } else if (args.length == 4) { // Used by D-Mason in order to restart a // worker after update, batch execution, reset autoStart = true; ip = args[0]; port = args[1]; topic = args[2]; if (args[3].equals("update")) { updated = true; } if (args[3].equals("reset")) { updated = false; isBatch = false; } if (args[3].contains("Batch")) { updated = false; isBatch = true; topicPrefix = args[3]; } } else { System.out.println("Usage: StartWorker IP PORT"); } DMasonWorker worker = new DMasonWorker(ip, port, topic); boolean connected = worker.startConnection(); if (connected) { logger.debug("CONNECTED:"); logger.debug(" IP : " + worker.ipAddress.getIPaddress()); logger.debug(" Port : " + worker.ipAddress.getPort()); logger.debug(" Prefix : " + DMasonWorker.topicPrefix); logger.debug(" Topic : " + worker.myTopic); } else { logger.info("CONNECTION FAILED:"); logger.debug(" IP : " + worker.ipAddress.getIPaddress()); logger.debug(" Port : " + worker.ipAddress.getPort()); logger.debug(" Prefix : " + DMasonWorker.topicPrefix); logger.debug(" Topic : " + worker.myTopic); } }
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 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 { 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:net.pandoragames.far.ui.swing.FindAndReplace.java
/** * The main method. Expects no arguments. * //w ww.j a va 2s .co m * @param args * not evaluated */ public static void main(String[] args) { if (FARConfig.getEffectiveJavaVersion() == 0) { // obscure jvm LogFactory.getLog(FindAndReplace.class) .warn("Java version could not be read. This may very well lead to unexpected crashes"); } else if (FARConfig.getEffectiveJavaVersion() < 5) { // won't work - // exit LogFactory.getLog(FindAndReplace.class) .error("FAR requires java 5 (1.5.x) or higher. Found 1." + FARConfig.getEffectiveJavaVersion()); System.exit(1); } else { LogFactory.getLog(FindAndReplace.class).debug("Running on java " + FARConfig.getEffectiveJavaVersion()); } JFrame.setDefaultLookAndFeelDecorated(SwingConfig.isMacOSX()); UIManager.put("Button.defaultButtonFollowsFocus", Boolean.TRUE); FindAndReplace far = new FindAndReplace(); far.configure(); far.init(); far.pack(); far.setVisible(true); // First time initialisation - speeds up the loading of the help views HelpView helpView = new HelpView(far, "About", "about.html", new Point(100, 100)); helpView.pack(); helpView.setVisible(false); if (args.length > 0 && SwingConfig.getEffectiveJavaVersion() > 5) { List<File> fileList = new ArrayList<File>(); for (String arg : args) { File file = new File(arg); if (file.exists()) fileList.add(file); } if (fileList.size() > 0) { far.fileImporter.importFiles(fileList); } } if (far.config.versionHasChanged()) { UpdateDialog updateWizzard = new UpdateDialog(far, far.config, far.componentRepository); if (updateWizzard.isUserInteractionRequired()) { updateWizzard.pack(); updateWizzard.setVisible(true); } else { updateWizzard.dispose(); } } }
From source file:com.justgiving.raven.kissmetrics.utils.KissmetricsRowParser.java
public static void main(String[] args) throws FileNotFoundException, IOException { for (String s : args) { System.out.println(s);/*from w ww .ja va 2s.c o m*/ } String inputFile = "D:\\datasets\\kissmetrics\\input\\2250.json"; String outputFile = "D:\\datasets\\kissmetrics\\output\\2250.json"; // String inputFile ="D:\\datasets\\kissmetrics\\input\\"; //String inputFile = "D:\\datasets\\kissmetrics\\input5\\"; //String outputFile = "D:\\datasets\\kissmetrics\\output5\\"; if (args.length == 2) { try { inputFile = args[0]; outputFile = args[1]; } catch (Exception e) { System.err.println( "Error unable to extract arguments, valid arguments are inputFilePath inputFilePath"); System.exit(1); } } else if (args == null || args.length == 0) { logger.info("using defaul values for inputFile=" + inputFile + " outputFile=" + outputFile); } String logConfigPath = Paths.get(System.getProperty("user.dir"), "log4j.properties").toString(); File f = new File(logConfigPath); if (f.exists() && !f.isDirectory()) { System.out.println("log config file used: " + logConfigPath); PropertyConfigurator.configure(logConfigPath); logger.info("log config file used: " + logConfigPath); } else { System.out.println( "no log file detected, please copy the log4j.properties to the same folder as the JAR"); } if (inputFile.endsWith("\\")) { logger.info("Detected folder"); processFolder(inputFile, outputFile); } else { logger.info("Detected file"); runonfileValidJson(inputFile, outputFile); } }
From source file:org.objectrepository.MessageConsumerDaemon.java
/** * main/*from w ww. ja v a 2 s . c o m*/ * <p/> * Accepts one folder as argument: -messageQueues * That folder ought to contain one or more folders ( or symbolic links ) to the files * The folder has the format: [foldername] or [foldername].[maxTasks] * MaxTasks is to indicate the total number of jobs being able to run. * * long * * @param argv */ public static void main(String[] argv) { if (instance == null) { final Properties properties = new Properties(); if (argv.length > 0) { for (int i = 0; i < argv.length; i += 2) { try { properties.put(argv[i], argv[i + 1]); } catch (ArrayIndexOutOfBoundsException arr) { System.out.println("Missing value after parameter " + argv[i]); System.exit(-1); } } } else { log.fatal("Usage: pmq-agent.jar -messageQueues [queues] -heartbeatInterval [interval in ms]\n" + "The queues is a folder that contains symbolic links to the startup scripts."); System.exit(-1); } if (log.isInfoEnabled()) { log.info("Arguments set: "); for (String key : properties.stringPropertyNames()) { log.info("'" + key + "'='" + properties.getProperty(key) + "'"); } } if (!properties.containsKey("-messageQueues")) { log.fatal("Expected case sensitive parameter: -messageQueues"); System.exit(-1); } final File messageQueues = new File((String) properties.get("-messageQueues")); if (!messageQueues.exists()) { log.fatal("Cannot find folder for messageQueues: " + messageQueues.getAbsolutePath()); System.exit(-1); } if (messageQueues.isFile()) { log.fatal( "-messageQueues should point to a folder, not a file: " + messageQueues.getAbsolutePath()); System.exit(-1); } long heartbeatInterval = 600000; if (properties.containsKey("-heartbeatInterval")) { heartbeatInterval = Long.parseLong((String) properties.get("heartbeatInterval")); } String identifier = null; if (properties.containsKey("-id")) { identifier = (String) properties.get("-id"); } else if (properties.containsKey("-identifier")) { identifier = (String) properties.get("-identifier"); } final File[] files = messageQueues.listFiles(); final String[] scriptNames = (properties.containsKey("-startup")) ? new String[] { properties.getProperty("-startup") } : new String[] { "/startup.sh", "\\startup.bat" }; final List<Queue> queues = new ArrayList<Queue>(); for (File file : files) { final String name = file.getName(); final String[] split = name.split("\\.", 2); final String queueName = split[0]; for (String scriptName : scriptNames) { final String shellScript = file.getAbsolutePath() + scriptName; final int maxTask = (split.length == 1) ? 1 : Integer.parseInt(split[1]); log.info("Candidate mq client for " + queueName + " maxTasks " + maxTask); if (new File(shellScript).exists()) { final Queue queue = new Queue(queueName, shellScript, false); queue.setCorePoolSize(1); queue.setMaxPoolSize(maxTask); queue.setQueueCapacity(1); queues.add(queue); break; } else { log.warn("... skipping, because no startup script found at " + shellScript); } } } if (queues.size() == 0) { log.fatal("No queue folders seen in " + messageQueues.getAbsolutePath()); System.exit(-1); } // Add the system queue queues.add(new Queue("Connection", null, true)); getInstance(queues, identifier, heartbeatInterval).run(); } System.exit(0); }
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 . ja v a 2s . 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); } } }