Example usage for java.io FileReader FileReader

List of usage examples for java.io FileReader FileReader

Introduction

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

Prototype

public FileReader(FileDescriptor fd) 

Source Link

Document

Creates a new FileReader , given the FileDescriptor to read, using the platform's java.nio.charset.Charset#defaultCharset() default charset .

Usage

From source file:com.tamingtext.classifier.mlt.MoreLikeThisCategorizer.java

public static void main(String[] args) throws Exception {
    DefaultOptionBuilder obuilder = new DefaultOptionBuilder();
    ArgumentBuilder abuilder = new ArgumentBuilder();
    GroupBuilder gbuilder = new GroupBuilder();

    Option helpOpt = DefaultOptionCreator.helpOption();

    Option inputDirOpt = obuilder.withLongName("input").withRequired(true)
            .withArgument(abuilder.withName("input").withMinimum(1).withMaximum(1).create())
            .withDescription("The input file to classify").withShortName("i").create();

    Option modelOpt = obuilder.withLongName("model").withRequired(true)
            .withArgument(abuilder.withName("index").withMinimum(1).withMaximum(1).create())
            .withDescription("The directory containing the index model").withShortName("m").create();

    Option categoryFieldOpt = obuilder.withLongName("categoryField").withRequired(true)
            .withArgument(abuilder.withName("index").withMinimum(1).withMaximum(1).create())
            .withDescription("Name of the field containing category information").withShortName("catf")
            .create();/*from   w ww  .  ja v a2s.c o  m*/

    Option contentFieldOpt = obuilder.withLongName("contentField").withRequired(true)
            .withArgument(abuilder.withName("index").withMinimum(1).withMaximum(1).create())
            .withDescription("Name of the field containing content information").withShortName("contf")
            .create();

    Option maxResultsOpt = obuilder.withLongName("maxResults").withRequired(false)
            .withArgument(abuilder.withName("gramSize").withMinimum(1).withMaximum(1).create())
            .withDescription("Number of results to retrive, default: 10 ").withShortName("r").create();

    Option gramSizeOpt = obuilder.withLongName("gramSize").withRequired(false)
            .withArgument(abuilder.withName("gramSize").withMinimum(1).withMaximum(1).create())
            .withDescription("Size of the n-gram. Default Value: 1 ").withShortName("ng").create();

    Option typeOpt = obuilder.withLongName("classifierType").withRequired(false)
            .withArgument(abuilder.withName("classifierType").withMinimum(1).withMaximum(1).create())
            .withDescription("Type of classifier: knn|tfidf. Default: bayes").withShortName("type").create();

    Group group = gbuilder.withName("Options").withOption(gramSizeOpt).withOption(helpOpt)
            .withOption(inputDirOpt).withOption(modelOpt).withOption(typeOpt).withOption(contentFieldOpt)
            .withOption(categoryFieldOpt).withOption(maxResultsOpt).create();

    try {
        Parser parser = new Parser();

        parser.setGroup(group);
        parser.setHelpOption(helpOpt);
        CommandLine cmdLine = parser.parse(args);
        if (cmdLine.hasOption(helpOpt)) {
            CommandLineUtil.printHelp(group);
            return;
        }

        String classifierType = (String) cmdLine.getValue(typeOpt);

        if (cmdLine.hasOption(gramSizeOpt)) {

        }

        int gramSize = 1;
        if (cmdLine.hasOption(gramSizeOpt)) {
            gramSize = Integer.parseInt((String) cmdLine.getValue(gramSizeOpt));
        }

        int maxResults = 10;
        if (cmdLine.hasOption(maxResultsOpt)) {
            maxResults = Integer.parseInt((String) cmdLine.getValue(maxResultsOpt));
        }

        String inputPath = (String) cmdLine.getValue(inputDirOpt);
        String modelPath = (String) cmdLine.getValue(modelOpt);
        String categoryField = (String) cmdLine.getValue(categoryFieldOpt);
        String contentField = (String) cmdLine.getValue(contentFieldOpt);

        MatchMode mode;

        if ("knn".equalsIgnoreCase(classifierType)) {
            mode = MatchMode.KNN;
        } else if ("tfidf".equalsIgnoreCase(classifierType)) {
            mode = MatchMode.TFIDF;
        } else {
            throw new IllegalArgumentException("Unkown classifierType: " + classifierType);
        }

        Reader reader = new FileReader(inputPath);
        Directory directory = FSDirectory.open(new File(modelPath));
        IndexReader indexReader = IndexReader.open(directory);
        MoreLikeThisCategorizer categorizer = new MoreLikeThisCategorizer(indexReader, categoryField);
        categorizer.setMatchMode(mode);
        categorizer.setFieldNames(new String[] { contentField });
        categorizer.setMaxResults(maxResults);

        if (gramSize > 1)
            categorizer.setNgramSize(gramSize);

        CategoryHits[] categories = categorizer.categorize(reader);
        for (CategoryHits c : categories) {
            System.out.println(c.getLabel() + "\t" + c.getHits() + "\t" + c.getScore());
        }

    } catch (OptionException e) {
        log.error("Error while parsing options", e);
    }
}

From source file:org.openmrs.module.custombranding.CustomBrandingUtils.java

public static Properties getThemeProperties(HttpServletRequest request) {
    Properties themeProps = new Properties();
    File themeFile = new File(getThemePath(request));
    File defaultThemeFile = new File(getDefaultThemePath(request));
    if (themeFile.exists() && defaultThemeFile.exists()) {
        try {//from   w  w  w .java2  s  .c om
            themeProps.load(new FileReader(defaultThemeFile));
            themeProps.load(new FileReader(themeFile));
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    return themeProps;
}

From source file:gov.nih.nci.ncicb.tcga.dcc.dam.dao.FileComparer.java

public static void compareFiles(String fname1, String fname2) throws IOException {

    Reader r1 = null;/*from   w  w  w.j a  va  2  s.c  o  m*/
    Reader r2 = null;

    try {
        File f1 = new File(fname1);
        File f2 = new File(fname2);
        //noinspection IOResourceOpenedButNotSafelyClosed
        r1 = new BufferedReader(new FileReader(f1));
        //noinspection IOResourceOpenedButNotSafelyClosed
        r2 = new BufferedReader(new FileReader(f2));
        int c1, c2;
        c1 = r1.read();
        c2 = r2.read();
        assertFalse("file1 has no content", c1 < 0);
        int i = 0;
        while (c1 != -1) {
            assertEquals("files are not equal at index " + i, c1, c2);
            c1 = r1.read();
            c2 = r2.read();
            ++i;
        }
    } finally {
        IOUtils.closeQuietly(r1);
        IOUtils.closeQuietly(r2);
    }
}

From source file:com.carteblanche.kwd.parsers.TestCaseParser.java

public static KWDTestCase parse(File csv, String cvsSplitBy) {

    BufferedReader br = null;//from  ww  w  . j a v a2 s.c  o m
    String line = "";
    String csvFile = csv.getAbsolutePath();

    try {

        File file = new File(csvFile);

        String testCaseName = file.getName();
        testCaseName = testCaseName.replace(".csv", "");
        testCaseName = StringUtils
                .capitalize(StringUtils.join(StringUtils.splitByCharacterTypeCamelCase(testCaseName), ' '));
        br = new BufferedReader(new FileReader(csvFile));
        ArrayList<KWDTestMethod> testMethods = new ArrayList<KWDTestMethod>();
        while ((line = br.readLine()) != null) {

            // use comma as separator
            String[] columns = line.split(cvsSplitBy);

            if (columns.length < 1) {
                System.out.println("Every row should have atleast 1 Column");
                System.exit(122);
            }

            ArrayList<String> parameters = new ArrayList<String>();
            for (int i = 1; i < columns.length; i++) {
                parameters.add(columns[i]);
            }
            KWDTestMethod testMethod = new KWDTestMethod(columns[0], parameters);
            testMethod.setClasssName("com.carteblanche.kwd.tests.Login");
            testMethods.add(testMethod);
        }
        KWDTestCase testCase = new KWDTestCase(testCaseName, testMethods);
        return testCase;
        // return new KWDTestSuite(testSuiteName, testcases);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return null;
}

From source file:com.opendoorlogistics.core.utils.io.TextIO.java

public static ODLDatastoreAlterable<ODLTableAlterable> importCSV(File file) {
    try {//from ww  w .ja  v a  2s . c om
        CSVReader reader = new CSVReader(new FileReader(file));
        return importFile(reader, getTableName(file));
    } catch (Throwable e) {
        throw new RuntimeException(e);
    }

}

From source file:Main.java

@SuppressWarnings("unchecked")
public static <T> T readXML(Class<?> class1, File file)
        throws JAXBException, IOException, SAXException, ParserConfigurationException {
    JAXBContext context = JAXBContext.newInstance(class1);
    Unmarshaller um = context.createUnmarshaller();

    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    spf.setFeature("http://xml.org/sax/features/validation", false);

    XMLReader xr = (XMLReader) spf.newSAXParser().getXMLReader();
    try (FileReader reader = new FileReader(file)) {
        SAXSource source = new SAXSource(xr, new InputSource(reader));

        T obj = (T) um.unmarshal(source);
        return obj;
    }/*from ww w .  j  a  va 2 s . c om*/
}

From source file:com.linkedin.pinot.tools.query.comparison.StatsGenerator.java

public static void generateReport(String dataFileName) throws IOException {
    List<DescriptiveStatistics> statisticsList = new ArrayList<>();

    String dataString;/*from w  w w .  j a v  a 2s.  c o  m*/
    BufferedReader dataReader = new BufferedReader(new FileReader(dataFileName));

    // First line is treated as header
    String[] columns = dataReader.readLine().split("\\s+");
    int numColumns = columns.length;

    for (int i = 0; i < numColumns; ++i) {
        statisticsList.add(new DescriptiveStatistics());
    }

    while ((dataString = dataReader.readLine()) != null) {
        String[] dataArray = dataString.trim().split(" ");

        if (dataArray.length != numColumns) {
            throw new RuntimeException("Row has missing columns: " + Arrays.toString(dataArray) + " Expected: "
                    + numColumns + " columns.");
        }

        for (int i = 0; i < dataArray.length; ++i) {
            double data = Double.valueOf(dataArray[i]);
            statisticsList.get(i).addValue(data);
        }
    }

    for (int i = 0; i < numColumns; i++) {
        LOGGER.info("Stats: {}: {}", columns[i], statisticsList.get(i).toString().replace("\n", "\t"));
    }
}

From source file:thesisdata.PieChartDemo1.java

/**
 * Creates a sample dataset./* w ww. jav a 2  s .  co m*/
 * 
 * @return A sample dataset.
 */
private static PieDataset createDataset() {
    DefaultPieDataset dataset = new DefaultPieDataset();
    try (BufferedReader br = new BufferedReader(new FileReader("summery.txt"))) {
        String line;

        while ((line = br.readLine()) != null) {
            String st[];
            st = line.split(" ");

            dataset.setValue(st[0], new Double(st[1]));

        }
    } catch (Exception ex) {
        // return dataset;
    }
    return dataset;
}

From source file:ai.serotonin.haystack.validator.Source.java

/**
 * Read a local diffs file./*from w w  w  . ja va2 s  .  co  m*/
 * 
 * @param filename
 * @return the list of rows found in the file.
 * @throws Exception
 */
public static List<HMap> diffs(String filename) throws Exception {
    BufferedReader in = new BufferedReader(new FileReader(filename));

    String line;
    List<HMap> rows = new ArrayList<>();
    while ((line = in.readLine()) != null) {
        if (line.startsWith("#"))
            // Comment. Skip.
            continue;

        if (line.startsWith("+"))
            rows.add(parseLine(line));
        else if (line.startsWith("^")) {
            HMap map = parseLine(line);

            // Find the existing row
            HReference id = map.id();
            for (HMap row : rows) {
                if (row.id().equals(id)) {
                    row.merge(map);
                    break;
                }
            }
        } else {
            System.out.println("Unknown line operation: " + line.charAt(0));
            continue;
        }
    }

    in.close();

    return rows;
}

From source file:MyServlet.java

public void init() throws ServletException {
    FileReader fileReader = null;
    BufferedReader bufferedReader = null;
    try {/* ww  w . ja  v  a 2 s  .  co m*/
        fileReader = new FileReader("InitDestroyCounter.initial");
        bufferedReader = new BufferedReader(fileReader);
        String initial = bufferedReader.readLine();
        count = Integer.parseInt(initial);
        bufferedReader.close();
        return;
    } catch (Exception ignored) {
    }

    String initial = getInitParameter("initial");
    try {
        count = Integer.parseInt(initial);
        return;
    } catch (NumberFormatException ignored) {
    } // null or non-integer value
    count = 0;
}