Example usage for java.io IOException IOException

List of usage examples for java.io IOException IOException

Introduction

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

Prototype

public IOException(Throwable cause) 

Source Link

Document

Constructs an IOException with the specified cause and a detail message of (cause==null ?

Usage

From source file:PIMInstallTester.java

public static void main(String[] a) throws Exception {
    String version = null;/*from  ww  w.  j  a v a 2s.c  o  m*/
    version = System.getProperty("microedition.pim.version");
    if (version != null) {
        if (!version.equals("1.0"))
            throw new IOException("Package is not version 1.0.");
    } else
        throw new IOException("PIM optional package is not available.");
}

From source file:MainClass.java

public static void main(String args[]) throws Exception {

    URL u = new URL("http://www.java2s.com/binary.dat");
    URLConnection uc = u.openConnection();
    String contentType = uc.getContentType();
    int contentLength = uc.getContentLength();
    if (contentType.startsWith("text/") || contentLength == -1) {
        throw new IOException("This is not a binary file.");
    }/*from w ww .j  a va  2  s . co  m*/
    InputStream raw = uc.getInputStream();
    InputStream in = new BufferedInputStream(raw);
    byte[] data = new byte[contentLength];
    int bytesRead = 0;
    int offset = 0;
    while (offset < contentLength) {
        bytesRead = in.read(data, offset, data.length - offset);
        if (bytesRead == -1)
            break;
        offset += bytesRead;
    }
    in.close();

    if (offset != contentLength) {
        throw new IOException("Only read " + offset + " bytes; Expected " + contentLength + " bytes");
    }

    String filename = u.getFile().substring(filename.lastIndexOf('/') + 1);
    FileOutputStream out = new FileOutputStream(filename);
    out.write(data);
    out.flush();
    out.close();
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    File file = new File("c:\\a.bat");
    InputStream is = new FileInputStream(file);

    long length = file.length();
    if (length > Integer.MAX_VALUE) {
        System.out.println("File is too large");
    }/* ww  w .jav  a  2  s  . co m*/

    byte[] bytes = new byte[(int) length];

    int offset = 0;
    int numRead = 0;
    while (numRead >= 0) {
        numRead = is.read(bytes, offset, bytes.length - offset);
        offset += numRead;
    }

    if (offset < bytes.length) {
        throw new IOException("Could not completely read file " + file.getName());
    }
    is.close();
    System.out.println(new String(bytes));
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(new File("testrss.xml"));

    Element root = doc.getDocumentElement();
    if (!root.getTagName().equalsIgnoreCase("rss")) {
        throw new IOException("Invalid RSS document");
    }/* w ww.  j a  v  a 2s. c  om*/
    List<RSSChannel> channels = readChannels(root.getChildNodes());
    for (RSSChannel channel : channels) {
        System.out.println("Channel: ");
        System.out.println("    title: " + channel.getTitle());
        System.out.println("    link: " + channel.getLink());
        System.out.println("    description: " + channel.getDescription());
        for (RSSItem item : channel.getItems()) {
            System.out.println("    Item: ");
            System.out.println("        title: " + item.getTitle());
            System.out.println("        link: " + item.getLink());
            System.out.println("        description: " + item.getDescription());
            System.out.println("        pubDate: " + item.getPubDate());
            System.out.println("        guid: " + item.getGuid());
        }
    }
}

From source file:cpm.openAtlas.bundleInfo.maker.BundleMakeBooter.java

public static void main(String[] args) throws JSONException, IOException {
    if (args.length != 2) {
        throw new IOException(" args to less , usage plugin_dir out_put_json_path");

    }//from  w  ww  .java  2 s.c o m

    String path = args[0];
    String targetFile = args[1];
    File dirFile = new File(path);
    JSONArray jsonArray = new JSONArray();
    File[] files = dirFile.listFiles();
    for (File file : files) {
        if (file.getAbsolutePath().contains("libcom")) {
            PackageLite packageLit = PackageLite.parse(file.getAbsolutePath());
            jsonArray.put(packageLit.getBundleInfo());
            //            try {
            //                packageLit.getBundleInfo().toString();
            //            } catch (JSONException e) {
            //               // TODO Auto-generated catch block
            //               e.printStackTrace();
            //            }
        }

    }
    org.apache.commons.io.FileUtils.writeStringToFile(new File(targetFile), jsonArray.toString());
    System.out.println(jsonArray.toString());
}

From source file:de.tudarmstadt.ukp.dkpro.core.mallet.lda.util.PrintTopWords.java

public static void main(String[] args) throws IOException {
    setOptions(args);//  w ww  .j  a  v a2  s . c  om
    String targetFile = modelFile + TARGET_FILE_SUFFIX;
    LOG.info(String.format("%nReading model from '%s'.%nStoring topic words in '%s'.", modelFile, targetFile));

    ParallelTopicModel model;
    try {
        model = ParallelTopicModel.read(modelFile);
    } catch (Exception e) {
        throw new IOException(e);
    }
    model.printTopWords(new File(targetFile), nWords + 1, false);
}

From source file:com.ibm.jaql.MiniCluster.java

/**
 * @param args//  ww w .jav a2 s. co m
 */
public static void main(String[] args) throws IOException {
    String clusterHome = System.getProperty("hadoop.minicluster.dir");
    if (clusterHome == null) {
        clusterHome = "./minicluster";
        System.setProperty("hadoop.minicluster.dir", clusterHome);
    }
    LOG.info("hadoop.minicluster.dir=" + clusterHome);
    File clusterFile = new File(clusterHome);
    if (!clusterFile.exists()) {
        clusterFile.mkdirs();
    }
    if (!clusterFile.isDirectory()) {
        throw new IOException("minicluster home directory must be a directory: " + clusterHome);
    }
    if (!clusterFile.canRead() || !clusterFile.canWrite()) {
        throw new IOException("minicluster home directory must be readable and writable: " + clusterHome);
    }

    String logDir = System.getProperty("hadoop.log.dir");
    if (logDir == null) {
        logDir = clusterHome + File.separator + "logs";
        System.setProperty("hadoop.log.dir", logDir);
    }
    File logFile = new File(logDir);
    if (!logFile.exists()) {
        logFile.mkdirs();
    }

    String confDir = System.getProperty("hadoop.conf.override");
    if (confDir == null) {
        confDir = clusterHome + File.separator + "conf";
        System.setProperty("hadoop.conf.override", confDir);
    }
    File confFile = new File(confDir);
    if (!confFile.exists()) {
        confFile.mkdirs();
    }

    System.out.println("starting minicluster in " + clusterHome);
    MiniCluster mc = new MiniCluster(args);
    // To find the ports in the 
    // hdfs: search for: Web-server up at: localhost:####
    // mapred: search for: mapred.JobTracker: JobTracker webserver: ####
    Configuration conf = mc.getConf();
    System.out.println("fs.default.name: " + conf.get("fs.default.name"));
    System.out.println("dfs.http.address: " + conf.get("dfs.http.address"));
    System.out.println("mapred.job.tracker.http.address: " + conf.get("mapred.job.tracker.http.address"));

    boolean waitForInterrupt;
    try {
        System.out.println("press enter to end minicluster (or eof to run forever)...");
        waitForInterrupt = System.in.read() < 0; // wait for any input or eof
    } catch (Exception e) {
        // something odd happened.  Just shutdown. 
        LOG.error("error reading from stdin", e);
        waitForInterrupt = false;
    }

    // eof means that we will wait for a kill signal
    while (waitForInterrupt) {
        System.out.println("minicluster is running until interrupted...");
        try {
            Thread.sleep(60 * 60 * 1000);
        } catch (InterruptedException e) {
            waitForInterrupt = false;
        }
    }

    System.out.println("shutting down minicluster...");
    try {
        mc.tearDown();
    } catch (Exception e) {
        LOG.error("error while shutting down minicluster", e);
    }
}

From source file:PDFDemo.java

public static void main(String[] argv) throws IOException {
    PrintWriter pout;//from w  w  w . j ava2s.co  m
    if (argv.length == 0) {
        pout = new PrintWriter(System.out);
    } else {
        if (new File(argv[0]).exists()) {
            throw new IOException("Output file " + argv[0] + " already exists");
        }
        pout = new PrintWriter(new FileWriter(argv[0]));
    }
    PDF p = new PDF(pout);
    Page p1 = new Page(p);
    p1.add(new MoveTo(p, 100, 600));
    p1.add(new Text(p, "Hello world, live on the web."));
    p1.add(new Text(p, "Hello world, line 2 on the web."));
    p.add(p1);
    p.setAuthor("Ian F. Darwin");
    p.writePDF();
}

From source file:com.svds.tailer2kafka.main.Main.java

/**
 * Given command-line arguments, create GenericConsumerGroup
 * //  w  ww.j a v  a2 s.  c  om
 * @param args  command-line arguments to parse
 * @throws IOException 
 */
public static void main(String[] args) throws IOException, InterruptedException {

    Options options = new Options();

    options.addOption(OptionBuilder.isRequired().withLongOpt(TOPICNAME).withDescription("Kafka topic name")
            .hasArg().create());

    options.addOption(OptionBuilder.isRequired().withLongOpt(METADATABROKERLIST)
            .withDescription("Kafka metadata.broker.list").hasArg().create());

    options.addOption(
            OptionBuilder.isRequired().withLongOpt(FILENAME).withDescription("Log filename").hasArg().create());

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);

    } catch (ParseException e) {
        LOG.error(e.getMessage(), e);
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("com.svds.tailer2kafka.main.Main", options);

        throw new IOException("Missing Args");
    }

    Main main = new Main();
    main.doWork(cmd);
}

From source file:examples.mail.IMAPImportMbox.java

public static void main(String[] args) throws IOException {
    if (args.length < 2) {
        System.err.println(//from w ww  .j  a v a 2  s  . co m
                "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);
}