Example usage for java.io FileReader read

List of usage examples for java.io FileReader read

Introduction

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

Prototype

public int read(java.nio.CharBuffer target) throws IOException 

Source Link

Document

Attempts to read characters into the specified character buffer.

Usage

From source file:nz.co.fortytwo.freeboard.server.util.ChartProcessor.java

/**
 * Reads the .kap file, and the generated tilesresource.xml to get
 * chart desc, bounding box, and zoom levels 
 * @param chartFile// w  w w. j a  v a 2  s .  c  om
 * @throws Exception
 */
public void processKapChart(File chartFile, boolean reTile) throws Exception {
    String chartName = chartFile.getName();
    chartName = chartName.substring(0, chartName.lastIndexOf("."));
    File dir = new File(chartFile.getParentFile(), chartName);
    if (manager) {
        System.out.print("Chart tag:" + chartName + "\n");
        System.out.print("Chart dir:" + dir.getPath() + "\n");
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Chart tag:" + chartName);
        logger.debug("Chart dir:" + dir.getPath());
    }
    //start by running the gdal scripts
    if (reTile) {
        executeGdal(chartFile, chartName,
                //this was for NZ KAP charts
                //Arrays.asList("gdal_translate", "-if","GTiff", "-of", "vrt", "-expand", "rgba",chartFile.getName(),"temp.vrt"),
                //this for US NOAA charts
                Arrays.asList("gdal_translate", "-of", "vrt", "-expand", "rgba", chartFile.getName(),
                        "temp.vrt"),
                Arrays.asList("gdal2tiles.py", "temp.vrt", chartName));
    }
    //now get the Chart Name from the kap file
    FileReader fileReader = new FileReader(chartFile);
    char[] chars = new char[4096];
    fileReader.read(chars);
    fileReader.close();
    String header = new String(chars);
    int pos = header.indexOf("BSB/NA=") + 7;
    String desc = header.substring(pos, header.indexOf("\n", pos)).trim();
    //if(desc.endsWith("\n"))desc=desc.substring(0,desc.length()-1);
    if (logger.isDebugEnabled())
        logger.debug("Name:" + desc);
    //we cant have + or , or = in name, as its used in storing ChartplotterViewModel
    //US50_2 BERING SEA CONTINUATION,NU=2401,RA=2746,3798,DU=254
    desc = desc.replaceAll("\\+", " ");
    desc = desc.replaceAll(",", " ");
    desc = desc.replaceAll("=", "/");
    //limit length too
    if (desc.length() > 40) {
        desc = desc.substring(0, 40);
    }
    //process the layer data

    //read data from dirName/tilelayers.xml
    SAXReader reader = new SAXReader();
    Document document = reader.read(new File(dir, "tilemapresource.xml"));
    //we need BoundingBox
    Element box = (Element) document.selectSingleNode("//BoundingBox");
    String minx = box.attribute("minx").getValue();
    String miny = box.attribute("miny").getValue();
    String maxx = box.attribute("maxx").getValue();
    String maxy = box.attribute("maxy").getValue();
    if (manager) {
        System.out.print("Box:" + minx + "," + miny + "," + maxx + "," + maxy + "\n");
    }
    if (logger.isDebugEnabled())
        logger.debug("Box:" + minx + "," + miny + "," + maxx + "," + maxy);

    //we need TileSets, each tileset has an href, we need first and last for zooms
    @SuppressWarnings("unchecked")
    List<Attribute> list = document.selectNodes("//TileSets/TileSet/@href");
    int minZoom = 18;
    int maxZoom = 0;
    for (Attribute attribute : list) {
        int zoom = Integer.valueOf(attribute.getValue());
        if (zoom < minZoom)
            minZoom = zoom;
        if (zoom > maxZoom)
            maxZoom = zoom;
    }
    if (manager) {
        System.out.print("Zoom:" + minZoom + "-" + maxZoom + "\n");
    }
    if (logger.isDebugEnabled())
        logger.debug("Zoom:" + minZoom + "-" + maxZoom);

    String snippet = "\n\tvar " + chartName + " = L.tileLayer(\"http://{s}.{server}:8080/mapcache/" + chartName
            + "/{z}/{x}/{y}.png\", {\n" + "\t\tserver: host,\n" + "\t\tsubdomains: 'abcd',\n"
            + "\t\tattribution: '" + chartName + " " + desc + "',\n" + "\t\tminZoom: " + minZoom + ",\n"
            + "\t\tmaxZoom: " + maxZoom + ",\n" + "\t\ttms: true\n" + "\t\t}).addTo(map);\n";

    if (manager) {
        System.out.print(snippet + "\n");
    }
    if (logger.isDebugEnabled())
        logger.debug(snippet);
    //add it to local freeboard.txt
    File layers = new File(dir, "freeboard.txt");
    FileUtils.writeStringToFile(layers, snippet);
    //now zip the result
    System.out.print("Zipping directory...\n");
    ZipUtils.zip(dir, new File(dir.getParentFile(), chartName + ".zip"));
    System.out.print("Zipping directory complete, in "
            + new File(dir.getParentFile(), chartName + ".zip").getAbsolutePath() + "\n");
    System.out.print("Conversion of " + chartName + " was completed successfully!\n");
}

From source file:jGPIO.DTO.java

/**
 * @param args/*from  w w w  .j  av a2  s.  c  o m*/
 */
public DTO() {
    // determine the OS Version
    try {
        FileReader procVersion = new FileReader("/proc/version");

        char[] buffer = new char[100];
        procVersion.read(buffer);
        procVersion.close();
        String fullVersion = new String(buffer);

        String re1 = "(Linux)"; // Word 1
        String re2 = "( )"; // Any Single Character 1
        String re3 = "(version)"; // Word 2
        String re4 = "( )"; // Any Single Character 2
        String re5 = "(\\d+)"; // Integer Number 1
        String re6 = "(\\.)"; // Any Single Character 3
        String re7 = "(\\d+)"; // Integer Number 2
        String re8 = "(\\.)"; // Any Single Character 4
        String re9 = "(\\d+)"; // Integer Number 3

        Pattern p = Pattern.compile(re1 + re2 + re3 + re4 + re5 + re6 + re7 + re8 + re9,
                Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
        Matcher m = p.matcher(fullVersion);
        if (m.find()) {
            Integer linuxMajor = Integer.parseInt(m.group(5));
            Integer linuxMinor = Integer.parseInt(m.group(7));

            if (linuxMajor >= 3 && linuxMinor >= 8) {
                requireDTO = true;
            }
        }

    } catch (FileNotFoundException e) {
        System.out.println("Couldn't read the /proc/version. Please check for why it doesn't exist!\n");
        System.exit(1);
    } catch (IOException e) {
        System.out.println("Couldn't read in from /proc/version. Please cat it to ensure it is valid\n");
    }

    // no DTO generation required, so we'll exit and the customer can check
    // for requireDTO to be false
    if (!requireDTO) {
        System.out.println("No need for DTO");
        return;
    }
    // load the file containing the GPIO Definitions from the property file
    try {
        definitionFile = System.getProperty("gpio_definition");
        // No definition file, try an alternative name
        if (definitionFile == null) {
            System.getProperty("gpio_definitions");
        }
        if (definitionFile == null) {
            // Still no definition file, try to autodetect it.
            definitionFile = autoDetectSystemFile();
        }
        JSONParser parser = new JSONParser();
        System.out.println("Using GPIO Definitions file: " + definitionFile);
        pinDefinitions = (JSONArray) parser.parse(new FileReader(definitionFile));
    } catch (NullPointerException NPE) {
        System.out.println(
                "Could not read the property for gpio_definition, please set this since you are on Linux kernel 3.8 or above");
        System.exit(-1);
    } catch (FileNotFoundException e) {
        System.out.println("Could not read the GPIO Definitions file");
        e.printStackTrace();
        System.exit(-1);
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(-1);
    } catch (ParseException e) {
        e.printStackTrace();
        System.exit(-1);
    }

}

From source file:org.sikuli.natives.LinuxUtil.java

private String[] findWindow(String appName, int winNum, SearchType type) {
    String[] found = {};//  w w  w.  j  av a2  s . co  m
    int numFound = 0;
    try {
        String cmd[] = { "wmctrl", "-lpGx" };
        Process p = Runtime.getRuntime().exec(cmd);
        InputStream in = p.getInputStream();
        BufferedReader bufin = new BufferedReader(new InputStreamReader(in));
        String str;

        int slash = appName.lastIndexOf("/");
        if (slash >= 0) {
            // remove path: /usr/bin/....
            appName = appName.substring(slash + 1);
        }

        if (type == SearchType.APP_NAME) {
            appName = appName.toLowerCase();
        }
        while ((str = bufin.readLine()) != null) {
            //Debug.log("read: " + str);
            String winLine[] = str.split("\\s+");
            boolean ok = false;

            if (type == SearchType.WINDOW_ID) {
                if (appName.equals(winLine[0])) {
                    ok = true;
                }
            } else if (type == SearchType.PID) {
                if (appName.equals(winLine[2])) {
                    ok = true;
                }
            } else if (type == SearchType.APP_NAME) {
                String pidFile = "/proc/" + winLine[2] + "/status";
                char buf[] = new char[1024];
                FileReader pidReader = null;
                try {
                    pidReader = new FileReader(pidFile);
                    pidReader.read(buf);
                    String pidName = new String(buf);
                    String nameLine[] = pidName.split("[:\n]");
                    String name = nameLine[1].trim();
                    if (name.equals(appName)) {
                        ok = true;
                    }

                } catch (FileNotFoundException e) {
                    // pid killed before we could read /proc/
                } finally {
                    if (pidReader != null) {
                        pidReader.close();
                    }
                }

                if (!ok && winLine[7].toLowerCase().contains(appName)) {
                    ok = true;
                }
            }

            if (ok) {
                if (numFound >= winNum) {
                    //Debug.log("Found window" + winLine);
                    found = winLine;
                    break;
                }
                numFound++;
            }
        }
        in.close();
        p.waitFor();
    } catch (Exception e) {
        System.out.println("[error] findWindow:\n" + e.getMessage());
        return null;
    }
    return found;
}

From source file:com.webcohesion.enunciate.EnunciateConfiguration.java

public String readGeneratedCodeLicenseFile() {
    License license = getGeneratedCodeLicense();
    String filePath = license == null ? null : license.getFile();
    if (filePath == null) {
        return null;
    }/* w  w w.  j a  v  a  2  s  .com*/

    File file = resolveFile(filePath);
    try {
        FileReader reader = new FileReader(file);
        StringWriter writer = new StringWriter();
        char[] chars = new char[100];
        int read = reader.read(chars);
        while (read >= 0) {
            writer.write(chars, 0, read);
        }
        reader.close();
        writer.close();
        return writer.toString();
    } catch (IOException e) {
        throw new EnunciateException(e);
    }
}

From source file:edu.umn.msi.tropix.common.test.FileUtilsTest.java

@Test(groups = "unit")
public void getFileReader() throws IOException {
    final FileOutputStream fos = new FileOutputStream(this.file);
    try {/* w ww .j a v  a2s.c o m*/
        fos.write("Hello".getBytes());
    } finally {
        fos.close();
    }
    final FileReader fr = this.fileUtils.getFileReader(this.file.getAbsolutePath());
    final char[] chars = new char[5];
    assert 5 == fr.read(chars);
    assert "Hello".equals(new String(chars));
}

From source file:org.eclipse.php.internal.ui.preferences.NewPHPManualSiteDialog.java

private String detectCHMLanguageSuffix(String chmFile) {
    StringBuilder suffix = new StringBuilder("::/"); //$NON-NLS-1$
    char[] buf = new char[8192];
    try {//from w w  w . j  a  va  2s.  c om
        FileReader r = new FileReader(chmFile);
        try {
            while (r.ready()) {
                r.read(buf);

                Matcher m = LANG_DETECT_PATTERN.matcher(new String(buf));
                if (m.find()) {
                    suffix.append(m.group(1));
                    break;
                }
            }
        } finally {
            r.close();
        }
    } catch (Exception e) {
    }
    return suffix.toString();
}

From source file:com.sun.faban.harness.webclient.Uploader.java

private String getRunIdTimestamp(String runId, String dir) {
    char[] cBuf = null;
    String[] status = new String[2];
    int length = -1;
    try {//  w ww .j a  va2s .c  om
        FileReader reader = new FileReader(dir + runId + '/' + Config.RESULT_INFO);
        cBuf = new char[128];
        length = reader.read(cBuf);
        reader.close();
    } catch (IOException e) {
        // Do nothing, length = -1.
    }
    String content = new String(cBuf, 0, length);
    int idx = content.indexOf('\t');
    if (idx != -1) {
        status[0] = content.substring(0, idx).trim();
        status[1] = content.substring(++idx).trim();
    } else {
        status[0] = content.trim();
    }
    return status[1];
}

From source file:com.supermap.desktop.icloud.CloudLicenseDialog.java

private void initToken() {
    FileReader reader = null;
    try {/*w  w w . j a  v  a2s .  co m*/
        File file = new File(TOKEN_PATH);
        if (file.exists()) {
            reader = new FileReader(file);
            char[] charArray = new char[(int) file.length()];
            reader.read(charArray);
            String[] token = String.valueOf(charArray).split(",");
            if (null != token && token.length == 4) {
                boolean savePassword = "true".equalsIgnoreCase(token[SAVE_TOKEN]);
                boolean autoLogin = "true".equalsIgnoreCase(token[AUTO_LOGIN]);
                checkBoxSavePassword.setSelected(savePassword);
                checkBoxAutoLogin.setSelected(autoLogin);
                if (savePassword) {
                    textFieldUserName.setText(token[USER_NAME]);
                    fieldPassWord.setText(token[PASS_WORD]);
                }
                if (autoLogin) {
                    buttonLogin.doClick();
                }
            }
        }

    } catch (FileNotFoundException e) {
        Application.getActiveApplication().getOutput().output(e);
    } catch (IOException e) {
        Application.getActiveApplication().getOutput().output(e);
    } finally {
        try {
            if (null != reader) {
                reader.close();
            }
        } catch (IOException e) {
            Application.getActiveApplication().getOutput().output(e);
        }
    }
}

From source file:org.ghost4j.analyzer.InkAnalyzer.java

/**
 * Performs ink analysis on a single page document.
 * //from  ww  w . j a v  a2s.c om
 * @param page
 *            Single page document
 * @return An AnalysisItem
 * @throws IOException
 * @throws AnalyzerException
 * @throws DocumentException
 */
private InkAnalysisItem analyzeSinglePage(Document page)
        throws IOException, AnalyzerException, DocumentException {

    // get Ghostscript instance
    Ghostscript gs = Ghostscript.getInstance();

    // generate a unique diskstore key for input and output
    DiskStore diskStore = DiskStore.getInstance();
    String inputDiskStoreKey = diskStore.generateUniqueKey();
    String outputDiskStoreKey = diskStore.generateUniqueKey();
    // write page to input file
    page.write(diskStore.addFile(inputDiskStoreKey));

    // prepare args
    // strange thing : result cannot be get with stdout (need to store in a
    // temp file)
    String[] gsArgs = { "-inkcov", "-dBATCH", "-dNOPAUSE", "-dQUIET", "-sDEVICE=inkcov",
            "-sOutputFile=" + diskStore.addFile(outputDiskStoreKey), "-f",
            diskStore.getFile(inputDiskStoreKey).getAbsolutePath() };

    FileReader fr = null;

    try {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        // execute and exit interpreter
        synchronized (gs) {
            gs.initialize(gsArgs);
            gs.exit();
        }

        // parse results from stdout
        fr = new FileReader(diskStore.getFile(outputDiskStoreKey));
        char[] chars = new char[100];
        fr.read(chars);
        String output = new String(chars).trim();
        InkAnalysisItem item = new InkAnalysisItem();

        // CMYK
        if (output.endsWith("CMYK OK")) {
            String[] components = output.split("CMYK")[0].split("  ");

            if (components.length == 4) {
                item.setC(this.parseValue(components[0]));
                item.setM(this.parseValue(components[1]));
                item.setY(this.parseValue(components[2]));
                item.setK(this.parseValue(components[3]));
            }
        }

        baos.close();

        return item;

    } catch (Exception e) {

        throw new AnalyzerException(e);

    } finally {

        IOUtils.closeQuietly(fr);

        // delete Ghostscript instance
        try {
            Ghostscript.deleteInstance();
        } catch (GhostscriptException e) {
            throw new AnalyzerException(e);
        }

        // remove temporary files
        diskStore.removeFile(inputDiskStoreKey);
        diskStore.removeFile(outputDiskStoreKey);
    }

}

From source file:com.gemstone.gemfire.management.internal.cli.commands.ConfigCommandsDUnitTest.java

@SuppressWarnings("serial")
public void testExportConfig() throws IOException {
    Properties localProps = new Properties();
    localProps.setProperty(DistributionConfig.NAME_NAME, "Manager");
    localProps.setProperty(DistributionConfig.GROUPS_NAME, "Group1");
    createDefaultSetup(localProps);/* w w w  . jav  a 2  s  .  co m*/

    // Create a cache in another VM (VM1)
    Host.getHost(0).getVM(1).invoke(new SerializableRunnable() {
        public void run() {
            Properties localProps = new Properties();
            localProps.setProperty(DistributionConfig.NAME_NAME, "VM1");
            localProps.setProperty(DistributionConfig.GROUPS_NAME, "Group2");
            getSystem(localProps);
            getCache();
        }
    });

    // Create a cache in a 3rd VM (VM2)
    Host.getHost(0).getVM(2).invoke(new SerializableRunnable() {
        public void run() {
            Properties localProps = new Properties();
            localProps.setProperty(DistributionConfig.NAME_NAME, "VM2");
            localProps.setProperty(DistributionConfig.GROUPS_NAME, "Group2");
            getSystem(localProps);
            getCache();
        }
    });

    // Create a cache in the local VM
    localProps = new Properties();
    localProps.setProperty(DistributionConfig.NAME_NAME, "Shell");
    getSystem(localProps);
    Cache cache = getCache();

    // Test export config for all members
    deleteTestFiles();
    CommandResult cmdResult = executeCommand("export config");
    assertEquals(Result.Status.OK, cmdResult.getStatus());

    assertTrue(this.managerConfigFile.exists());
    assertTrue(this.managerPropsFile.exists());
    assertTrue(this.vm1ConfigFile.exists());
    assertTrue(this.vm1PropsFile.exists());
    assertTrue(this.vm2ConfigFile.exists());
    assertTrue(this.vm2PropsFile.exists());
    assertTrue(this.shellConfigFile.exists());
    assertTrue(this.shellPropsFile.exists());

    // Test exporting member
    deleteTestFiles();
    cmdResult = executeCommand("export config --member=Manager");
    assertEquals(Result.Status.OK, cmdResult.getStatus());

    assertTrue(this.managerConfigFile.exists());
    assertFalse(this.vm1ConfigFile.exists());
    assertFalse(this.vm2ConfigFile.exists());
    assertFalse(this.shellConfigFile.exists());

    // Test exporting group
    deleteTestFiles();
    cmdResult = executeCommand("export config --group=Group2");
    assertEquals(Result.Status.OK, cmdResult.getStatus());

    assertFalse(this.managerConfigFile.exists());
    assertTrue(this.vm1ConfigFile.exists());
    assertTrue(this.vm2ConfigFile.exists());
    assertFalse(this.shellConfigFile.exists());

    // Test export to directory
    deleteTestFiles();
    cmdResult = executeCommand("export config --dir=" + subDir.getAbsolutePath());
    assertEquals(Result.Status.OK, cmdResult.getStatus());

    assertFalse(this.managerConfigFile.exists());
    assertTrue(this.subManagerConfigFile.exists());

    // Test the contents of the file
    StringWriter stringWriter = new StringWriter();
    PrintWriter printWriter = new PrintWriter(stringWriter);
    CacheXmlGenerator.generate(cache, printWriter, false, false, false);
    String configToMatch = stringWriter.toString();

    deleteTestFiles();
    cmdResult = executeCommand("export config --member=Shell");
    assertEquals(Result.Status.OK, cmdResult.getStatus());

    char[] fileContents = new char[configToMatch.length()];
    try {
        FileReader reader = new FileReader(shellConfigFile);
        reader.read(fileContents);
    } catch (Exception ex) {
        fail("Unable to read file contents for comparison", ex);
    }

    assertEquals(configToMatch, new String(fileContents));
}