List of usage examples for java.io File canRead
public boolean canRead()
From source file:Main.java
public static void main(String[] args) { File f = new File("C:/test.txt"); // set read permission boolean bool = f.setReadable(true, true); System.out.println("setReadable() succeeded?: " + bool); // checks whether the file is readable bool = f.canRead(); System.out.print("Is file readable?: " + bool); }
From source file:net.sf.jsignpdf.verify.SignatureCounter.java
/** * Main program.//w ww .j av a 2s .co m * * @param args */ public static void main(String[] args) { // create the Options final Option optHelp = new Option("h", "help", false, "print this message"); final Option optDebug = new Option("d", "debug", false, "enables debug output"); final Option optNames = new Option("n", "names", false, "print comma separated signature names instead of the count"); final Option optPasswd = new Option("p", "password", true, "set password for opening PDF"); optPasswd.setArgName("password"); final Options options = new Options(); options.addOption(optHelp); options.addOption(optDebug); options.addOption(optNames); options.addOption(optPasswd); CommandLine line = null; try { // create the command line parser CommandLineParser parser = new PosixParser(); // parse the command line arguments line = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Unable to parse command line (Use -h for the help)\n" + exp.getMessage()); System.exit(Constants.EXIT_CODE_PARSE_ERR); } final String[] tmpArgs = line.getArgs(); if (line.hasOption("h") || args == null || args.length == 0) { // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(70, "java -jar SignatureCounter.jar [file1.pdf [file2.pdf ...]]", "JSignPdf SignatureCounter is a command line tool which prints count of signatures in given PDF document.", options, null, true); } else { byte[] tmpPasswd = null; if (line.hasOption("p")) { tmpPasswd = line.getOptionValue("p").getBytes(); } final boolean debug = line.hasOption("d"); final boolean names = line.hasOption("n"); for (String tmpFilePath : tmpArgs) { if (debug) { System.out.print("Counting signatures in " + tmpFilePath + ": "); } final File tmpFile = new File(tmpFilePath); if (!tmpFile.canRead()) { System.err.println("Couldn't read the file. Check the path and permissions: " + tmpFilePath); System.exit(Constants.EXIT_CODE_CANT_READ_FILE); } try { final PdfReader pdfReader = PdfUtils.getPdfReader(tmpFilePath, tmpPasswd); @SuppressWarnings("unchecked") final List<String> sigNames = pdfReader.getAcroFields().getSignatureNames(); if (names) { //print comma-separated names boolean isNotFirst = false; for (String sig : sigNames) { if (isNotFirst) { System.out.println(","); } else { isNotFirst = true; } System.out.println(sig); } } else { //normal processing print only count of signatures System.out.println(sigNames.size()); if (debug) { System.out.println("Signature names: " + sigNames); } } } catch (IOException e) { e.printStackTrace(); System.exit(Constants.EXIT_CODE_COMMON_ERROR); } } } }
From source file:cmd.freebase2rdf.java
public static void main(String[] args) throws Exception { if (args.length != 2) { usage();// w w w . j a va 2 s . c om } File input = new File(args[0]); if (!input.exists()) error("File " + input.getAbsolutePath() + " does not exist."); if (!input.canRead()) error("Cannot read file " + input.getAbsolutePath()); if (!input.isFile()) error("Not a file " + input.getAbsolutePath()); File output = new File(args[1]); if (output.exists()) error("Output file " + output.getAbsolutePath() + " already exists, this program do not override existing files."); if (output.canWrite()) error("Cannot write file " + output.getAbsolutePath()); if (output.isDirectory()) error("Not a file " + output.getAbsolutePath()); if (!output.getName().endsWith(".nt.gz")) error("Output filename should end with .nt.gz, this is the only format supported."); BufferedReader in = new BufferedReader( new InputStreamReader(new BZip2CompressorInputStream(new FileInputStream(input)))); BufferedOutputStream out = new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream(output))); String line; ProgressLogger progressLogger = new ProgressLogger(log, "lines", 100000, 1000000); progressLogger.start(); Freebase2RDF freebase2rdf = null; try { freebase2rdf = new Freebase2RDF(out); while ((line = in.readLine()) != null) { freebase2rdf.send(line); progressLogger.tick(); } } finally { if (freebase2rdf != null) freebase2rdf.close(); } print(log, progressLogger); }
From source file:de.berber.kindle.annotator.Main.java
/** * Main function of PDFAnnotator. For command line parameters see the {@see * Options} class./* www . ja v a 2 s .co m*/ * * @param args * List of command line parameters. */ public static void main(String[] args) { final CompositeConfiguration cc = new CompositeConfiguration(); try { // configure logging final PatternLayout layout = new PatternLayout("%d{ISO8601} %-5p [%t] %c: %m%n"); final ConsoleAppender consoleAppender = new ConsoleAppender(layout); Logger.getRootLogger().addAppender(consoleAppender); Logger.getRootLogger().setLevel(Level.WARN); // read commandline final Options options = new Options(); final CmdLineParser parser = new CmdLineParser(options); parser.setUsageWidth(80); try { // parse the arguments. parser.parseArgument(args); if (options.help) { parser.printUsage(System.err); return; } } catch (CmdLineException e) { // if there's a problem in the command line, // you'll get this exception. this will report // an error message. System.err.println(e.getMessage()); System.err.println("Usage:"); // print the list of available options parser.printUsage(System.err); System.err.println(); // print option sample. This is useful some time System.err.println(" Example: java -jar <jar> " + parser.printExample(ExampleMode.ALL)); return; } // read default configuration file final URL defaultURL = PDFAnnotator.class.getClassLoader() .getResource("de/berber/kindle/annotator/PDFAnnotator.default"); // read config file specified at the command line if (options.config != null) { final File configFile = new File(options.config); if (!configFile.exists() || !configFile.canRead()) { LOG.error("Specified configuration file does not exist."); } else { cc.addConfiguration(new PropertiesConfiguration(configFile)); } } cc.addConfiguration(new PropertiesConfiguration(defaultURL)); final WorkingList model = new WorkingList(); final WorkQueue queue = new WorkQueue(cc, model); AbstractMain view = null; if (options.noGUI) { view = new BatchMain(options, model); } else { view = new MainWindow(options, model); } view.run(); if (options.noGUI) { queue.stop(); } } catch (Exception ex) { LOG.error("Error while executing Kindle Annotator. Please report a bug."); ex.printStackTrace(); } }
From source file:de.cwclan.cwsa.serverendpoint.main.ServerEndpoint.java
/** * @param args the command line arguments *//*from w w w . ja va2 s .c o m*/ public static void main(String[] args) { Options options = new Options(); options.addOption(OptionBuilder.withArgName("file").hasArg().withDescription( "Used to enter path of configfile. Default file is endpoint.properties. NOTE: If the file is empty or does not exsist, a default config is created.") .create("config")); options.addOption("h", "help", false, "displays this page"); CommandLineParser parser = new PosixParser(); Properties properties = new Properties(); try { /* * parse default config shipped with jar */ CommandLine cmd = parser.parse(options, args); /* * load default configuration */ InputStream in = ServerEndpoint.class.getResourceAsStream("/endpoint.properties"); if (in == null) { throw new IOException("Unable to load default config from JAR. This should not happen."); } properties.load(in); in.close(); log.debug("Loaded default config base: {}", properties.toString()); if (cmd.hasOption("help")) { printHelp(options); System.exit(0); } /* * parse cutom config if exists, otherwise create default cfg */ if (cmd.hasOption("config")) { File file = new File(cmd.getOptionValue("config", "endpoint.properties")); if (file.exists() && file.canRead() && file.isFile()) { in = new FileInputStream(file); properties.load(in); log.debug("Loaded custom config from {}: {}", file.getAbsoluteFile(), properties); } else { log.warn("Config file does not exsist. A default file will be created."); } FileWriter out = new FileWriter(file); properties.store(out, "Warning, this file is recreated on every startup to merge missing parameters."); } /* * create and start endpoint */ log.info("Config read successfull. Values are: {}", properties); ServerEndpoint endpoint = new ServerEndpoint(properties); Runtime.getRuntime().addShutdownHook(endpoint.getShutdownHook()); endpoint.start(); } catch (IOException ex) { log.error("Error while reading config.", ex); } catch (ParseException ex) { log.error("Error while parsing commandline options: {}", ex.getMessage()); printHelp(options); System.exit(1); } }
From source file:LauncherBootstrap.java
/** * The main method.// w ww . j a v a2 s . c om * * @param args command line arguments */ public static void main(String[] args) { try { // Try to find the LAUNCHER_JAR_FILE_NAME file in the class // loader's and JVM's classpath. URL coreURL = LauncherBootstrap.class.getResource("/" + LauncherBootstrap.LAUNCHER_JAR_FILE_NAME); if (coreURL == null) throw new FileNotFoundException(LauncherBootstrap.LAUNCHER_JAR_FILE_NAME); // Coerce the coreURL's directory into a file File coreDir = new File(URLDecoder.decode(coreURL.getFile())).getCanonicalFile().getParentFile(); // Try to find the LAUNCHER_PROPS_FILE_NAME file in the same // directory as this class File propsFile = new File(coreDir, LauncherBootstrap.LAUNCHER_PROPS_FILE_NAME); if (!propsFile.canRead()) throw new FileNotFoundException(propsFile.getPath()); // Load the properties in the LAUNCHER_PROPS_FILE_NAME Properties props = new Properties(); FileInputStream fis = new FileInputStream(propsFile); props.load(fis); fis.close(); // Create a class loader that contains the Launcher, Ant, and // JAXP classes. URL[] antURLs = LauncherBootstrap .fileListToURLs((String) props.get(LauncherBootstrap.ANT_CLASSPATH_PROP_NAME)); URL[] urls = new URL[1 + antURLs.length]; urls[0] = coreURL; for (int i = 0; i < antURLs.length; i++) urls[i + 1] = antURLs[i]; ClassLoader parentLoader = Thread.currentThread().getContextClassLoader(); URLClassLoader loader = null; if (parentLoader != null) loader = new URLClassLoader(urls, parentLoader); else loader = new URLClassLoader(urls); // Load the LAUNCHER_MAIN_CLASS_NAME class launcherClass = loader.loadClass(LAUNCHER_MAIN_CLASS_NAME); // Get the LAUNCHER_MAIN_CLASS_NAME class' getLocalizedString() // method as we need it for printing the usage statement Method getLocalizedStringMethod = launcherClass.getDeclaredMethod("getLocalizedString", new Class[] { String.class }); // Invoke the LAUNCHER_MAIN_CLASS_NAME class' start() method. // If the ant.class.path property is not set correctly in the // LAUNCHER_PROPS_FILE_NAME, this will throw an exception. Method startMethod = launcherClass.getDeclaredMethod("start", new Class[] { String[].class }); int returnValue = ((Integer) startMethod.invoke(null, new Object[] { args })).intValue(); // Always exit cleanly after invoking the start() method System.exit(returnValue); } catch (Throwable t) { t.printStackTrace(); System.exit(1); } }
From source file:examples.mail.IMAPImportMbox.java
public static void main(String[] args) throws IOException { if (args.length < 2) { System.err.println(/*from ww w .j a v a2s . c om*/ "Usage: IMAPImportMbox imap[s]://user:password@host[:port]/folder/path <mboxfile> [selectors]"); System.err.println("\tWhere: a selector is a list of numbers/number ranges - 1,2,3-10" + " - or a list of strings to match in the initial From line"); System.exit(1); } final URI uri = URI.create(args[0]); final String file = args[1]; final File mbox = new File(file); if (!mbox.isFile() || !mbox.canRead()) { throw new IOException("Cannot read mailbox file: " + mbox); } String path = uri.getPath(); if (path == null || path.length() < 1) { throw new IllegalArgumentException("Invalid folderPath: '" + path + "'"); } String folder = path.substring(1); // skip the leading / List<String> contains = new ArrayList<String>(); // list of strings to find BitSet msgNums = new BitSet(); // list of message numbers for (int i = 2; i < args.length; i++) { String arg = args[i]; if (arg.matches("\\d+(-\\d+)?(,\\d+(-\\d+)?)*")) { // number,m-n for (String entry : arg.split(",")) { String[] parts = entry.split("-"); if (parts.length == 2) { // m-n int low = Integer.parseInt(parts[0]); int high = Integer.parseInt(parts[1]); for (int j = low; j <= high; j++) { msgNums.set(j); } } else { msgNums.set(Integer.parseInt(entry)); } } } else { contains.add(arg); // not a number/number range } } // System.out.println(msgNums.toString()); // System.out.println(java.util.Arrays.toString(contains.toArray())); // Connect and login final IMAPClient imap = IMAPUtils.imapLogin(uri, 10000, null); int total = 0; int loaded = 0; try { imap.setSoTimeout(6000); final BufferedReader br = new BufferedReader(new FileReader(file)); // TODO charset? String line; StringBuilder sb = new StringBuilder(); boolean wanted = false; // Skip any leading rubbish while ((line = br.readLine()) != null) { if (line.startsWith("From ")) { // start of message; i.e. end of previous (if any) if (process(sb, imap, folder, total)) { // process previous message (if any) loaded++; } sb.setLength(0); total++; wanted = wanted(total, line, msgNums, contains); } else if (startsWith(line, PATFROM)) { // Unescape ">+From " in body text line = line.substring(1); } // TODO process first Received: line to determine arrival date? if (wanted) { sb.append(line); sb.append(CRLF); } } br.close(); if (wanted && process(sb, imap, folder, total)) { // last message (if any) loaded++; } } catch (IOException e) { System.out.println(imap.getReplyString()); e.printStackTrace(); System.exit(10); return; } finally { imap.logout(); imap.disconnect(); } System.out.println("Processed " + total + " messages, loaded " + loaded); }
From source file:com.nohowdezign.gcpmanager.Main.java
public final static void main(String[] args) { //Remove old log, it does not need to be there anymore. File oldLog = new File("./CloudPrintManager.log"); if (oldLog.exists()) { oldLog.delete();/* w w w . j a va2 s. c o m*/ } //Create a file reader for the props file Reader propsStream = null; try { propsStream = new FileReader("./props.json"); } catch (FileNotFoundException e1) { e1.printStackTrace(); } PrintManagerProperties props = null; if (propsStream != null) { props = gson.fromJson(propsStream, PrintManagerProperties.class); } else { logger.error("Property file does not exist. Please create one."); } //Set the variables to what is in the props file String email = props.getEmail(); String password = props.getPassword(); String printerId = props.getPrinterId(); amountOfPagesPerPrintJob = props.getAmountOfPagesPerPrintJob(); timeRestraintsForPrinter = props.getTimeRestraintsForPrinter(); JobStorageManager.timeToKeepFileInDays = props.getTimeToKeepFileInDays(); //AuthenticationManager authenticationManager = new AuthenticationManager(); //authenticationManager.setPasswordToUse(props.getAdministrativePassword()); //authenticationManager.initialize(1337); //Start the authentication manager on port 1337 try { cloudPrint.connect(email, password, "cloudprintmanager-1.0"); } catch (CloudPrintAuthenticationException e) { logger.error(e.getMessage()); } //TODO: Get a working website ready //Thread adminConsole = new Thread(new HttpServer(80), "HttpServer"); //adminConsole.start(); Thread printJobManager = new Thread(new JobStorageManagerThread(), "JobStorageManager"); printJobManager.start(); try { if (System.getProperty("os.name").toLowerCase().startsWith("win")) { logger.error("Your operating system is not supported. Please switch to linux ya noob."); System.exit(1); } else { PrinterManager printerManager = new PrinterManager(cloudPrint); File cupsPrinterDir = new File("/etc/cups/ppd"); if (cupsPrinterDir.isDirectory() && cupsPrinterDir.canRead()) { for (File cupsPrinterPPD : cupsPrinterDir.listFiles()) { //Init all of the CUPS printers in the manager printerManager.initializePrinter(cupsPrinterPPD, cupsPrinterPPD.getName()); } } else { logger.error("Please run this with a higher access level."); System.exit(1); } } } catch (Exception e) { e.printStackTrace(); } while (true) { try { getPrintingJobs(printerId); } catch (Exception e) { e.printStackTrace(); } } }
From source file:Main.java
/** Index all text files under a directory. */ public static void main(String[] args) { String usage = "java IndexFiles" + " [-index INDEX_PATH] [-docs DOCS_PATH] [-update]\n\n" + "This indexes the documents in DOCS_PATH, creating a Lucene index" + "in INDEX_PATH that can be searched with SearchFiles"; String indexPath = "index"; String docsPath = null;/*from w ww .j a v a2s .c o m*/ boolean create = true; for (int i = 0; i < args.length; i++) { if ("-index".equals(args[i])) { indexPath = args[i + 1]; i++; } else if ("-docs".equals(args[i])) { docsPath = args[i + 1]; i++; } else if ("-update".equals(args[i])) { create = false; } } if (docsPath == null) { System.err.println("Usage: " + usage); System.exit(1); } final File docDir = new File(docsPath); if (!docDir.exists() || !docDir.canRead()) { System.out.println("Document directory '" + docDir.getAbsolutePath() + "' does not exist or is not readable, please check the path"); System.exit(1); } Date start = new Date(); try { System.out.println("Indexing to directory '" + indexPath + "'..."); Directory dir = FSDirectory.open(new File(indexPath)); // :Post-Release-Update-Version.LUCENE_XY: Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_4_10_0); IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_4_10_0, analyzer); if (create) { // Create a new index in the directory, removing any // previously indexed documents: iwc.setOpenMode(OpenMode.CREATE); } else { // Add new documents to an existing index: iwc.setOpenMode(OpenMode.CREATE_OR_APPEND); } // Optional: for better indexing performance, if you // are indexing many documents, increase the RAM // buffer. But if you do this, increase the max heap // size to the JVM (eg add -Xmx512m or -Xmx1g): // // iwc.setRAMBufferSizeMB(256.0); IndexWriter writer = new IndexWriter(dir, iwc); indexDocs(writer, docDir); // NOTE: if you want to maximize search performance, // you can optionally call forceMerge here. This can be // a terribly costly operation, so generally it's only // worth it when your index is relatively static (ie // you're done adding documents to it): // // writer.forceMerge(1); writer.close(); Date end = new Date(); System.out.println(end.getTime() - start.getTime() + " total milliseconds"); } catch (IOException e) { System.out.println(" caught a " + e.getClass() + "\n with message: " + e.getMessage()); } }
From source file:com.turn.ttorrent.cli.TorrentMain.java
/** * Torrent reader and creator./*from w ww . j av a 2s .c om*/ * * <p> * You can use the {@code main()} function of this class to read or create * torrent files. See usage for details. * </p> * */ public static void main(String[] args) { BasicConfigurator.configure(new ConsoleAppender(new PatternLayout("%-5p: %m%n"))); CmdLineParser parser = new CmdLineParser(); CmdLineParser.Option help = parser.addBooleanOption('h', "help"); CmdLineParser.Option filename = parser.addStringOption('t', "torrent"); CmdLineParser.Option create = parser.addBooleanOption('c', "create"); CmdLineParser.Option pieceLength = parser.addIntegerOption('l', "length"); CmdLineParser.Option announce = parser.addStringOption('a', "announce"); try { parser.parse(args); } catch (CmdLineParser.OptionException oe) { System.err.println(oe.getMessage()); usage(System.err); System.exit(1); } // Display help and exit if requested if (Boolean.TRUE.equals((Boolean) parser.getOptionValue(help))) { usage(System.out); System.exit(0); } String filenameValue = (String) parser.getOptionValue(filename); if (filenameValue == null) { usage(System.err, "Torrent file must be provided!"); System.exit(1); } Integer pieceLengthVal = (Integer) parser.getOptionValue(pieceLength); if (pieceLengthVal == null) { pieceLengthVal = Torrent.DEFAULT_PIECE_LENGTH; } else { pieceLengthVal = pieceLengthVal * 1024; } logger.info("Using piece length of {} bytes.", pieceLengthVal); Boolean createFlag = (Boolean) parser.getOptionValue(create); //For repeated announce urls @SuppressWarnings("unchecked") Vector<String> announceURLs = (Vector<String>) parser.getOptionValues(announce); String[] otherArgs = parser.getRemainingArgs(); if (Boolean.TRUE.equals(createFlag) && (otherArgs.length != 1 || announceURLs.isEmpty())) { usage(System.err, "Announce URL and a file or directory must be " + "provided to create a torrent file!"); System.exit(1); } OutputStream fos = null; try { if (Boolean.TRUE.equals(createFlag)) { if (filenameValue != null) { fos = new FileOutputStream(filenameValue); } else { fos = System.out; } //Process the announce URLs into URIs List<URI> announceURIs = new ArrayList<URI>(); for (String url : announceURLs) { announceURIs.add(new URI(url)); } //Create the announce-list as a list of lists of URIs //Assume all the URI's are first tier trackers List<List<URI>> announceList = new ArrayList<List<URI>>(); announceList.add(announceURIs); File source = new File(otherArgs[0]); if (!source.exists() || !source.canRead()) { throw new IllegalArgumentException( "Cannot access source file or directory " + source.getName()); } String creator = String.format("%s (ttorrent)", System.getProperty("user.name")); Torrent torrent = null; if (source.isDirectory()) { List<File> files = new ArrayList<File>( FileUtils.listFiles(source, TrueFileFilter.TRUE, TrueFileFilter.TRUE)); Collections.sort(files); torrent = Torrent.create(source, files, pieceLengthVal, announceList, creator); } else { torrent = Torrent.create(source, pieceLengthVal, announceList, creator); } torrent.save(fos); } else { Torrent.load(new File(filenameValue), true); } } catch (Exception e) { logger.error("{}", e.getMessage(), e); System.exit(2); } finally { if (fos != System.out) { IOUtils.closeQuietly(fos); } } }