Java Examples for java.io.InputStreamReader

The following java examples will help you to understand the usage of java.io.InputStreamReader. These source code samples are taken from different open source projects.

Example 1
Project: android-platform-tools-base-master  File: Main.java View source code
public static String getContent() {
    InputStream input = Main.class.getResourceAsStream("/first_pick.txt");
    if (input == null) {
        return "FAILED TO FIND first_pick.txt";
    }
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
        return reader.readLine();
    } catch (IOException e) {
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
            }
        }
    }
    return "FAILED TO READ CONTENT";
}
Example 2
Project: jeql-master  File: IOUtil.java View source code
public static String readFile(String filename, boolean addEOL) throws IOException {
    StringBuffer buf = new StringBuffer();
    BufferedReader bufReader = null;
    try {
        FileInputStream fis = new FileInputStream(filename);
        bufReader = new BufferedReader(new InputStreamReader(fis));
        String line = "";
        while ((line = bufReader.readLine()) != null) {
            buf.append(line);
            // possibly add EOL char to each line
            if (addEOL)
                buf.append('\n');
        }
    // System.out.println(buf);
    } finally {
        if (bufReader != null)
            bufReader.close();
    }
    // may be empty string if an error occurred
    return buf.toString();
}
Example 3
Project: checkstyle-master  File: InputFinalInTryWithResource.java View source code
public static void test() {
    try {
    } catch (RuntimeException e) {
    }
    try (@NotNull BufferedReader br = new BufferedReader(new InputStreamReader(null, "utf-8"))) {
    } catch (IOException e) {
    }
    try (final BufferedReader br = new BufferedReader(new InputStreamReader(null, "utf-8"))) {
    } catch (IOException e) {
    }
    try (final BufferedReader br = new BufferedReader(new InputStreamReader(null, "utf-8"));
        final BufferedReader br2 = new BufferedReader(new InputStreamReader(null, "utf-8"))) {
    } catch (IOException e) {
    }
}
Example 4
Project: TFC2-master  File: JSONReader.java View source code
public boolean read(File file) {
    try {
        Gson gson = new Gson();
        InputStream stream;
        if (file == null)
            stream = this.getClass().getResourceAsStream(path);
        else if (file.exists()) {
            stream = Files.asByteSource(file).openStream();
        } else {
            return false;
        }
        InputStreamReader sr = new InputStreamReader(stream);
        JsonReader reader = new JsonReader(sr);
        process(reader);
        reader.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return true;
}
Example 5
Project: ocr-tools-master  File: TextMerger.java View source code
@Override
public void merge(List<InputStream> inputs, OutputStream output) {
    try {
        OutputStreamWriter osw = new OutputStreamWriter(output, "UTF-8");
        // Ascii page break dec 12, hex 0c
        char pb = (char) 12;
        // Use the platform dependent separator here
        String seperator = System.getProperty("line.separator");
        int f = 0;
        while (f < inputs.size()) {
            InputStreamReader isr = new InputStreamReader(inputs.get(f), "UTF-8");
            BufferedReader br = new BufferedReader(isr);
            String line;
            while ((line = br.readLine()) != null) {
                osw.write(line);
                osw.write(seperator);
            }
            //osw.write(pb);
            br.close();
            isr.close();
            f++;
        }
        osw.close();
    } catch (IOException e) {
        throw new IllegalStateException("Error while merging files.", e);
    }
}
Example 6
Project: Mint-Programming-Language-master  File: ExecuteJava.java View source code
@Override
public Pointer apply(SmartList<Pointer> args) throws MintException {
    String programName = PointerTools.dereferenceString(args.get(0));
    programName = programName.trim();
    String className = programName.replace(".java", "");
    if (!programName.endsWith(".java")) {
        programName += ".java";
    }
    try {
        Process jv = Runtime.getRuntime().exec("javac " + programName);
        Process jv2 = Runtime.getRuntime().exec("java " + className);
        BufferedReader in = new BufferedReader(new InputStreamReader(jv2.getInputStream()));
        String line = null;
        int i = 0;
        int limit = Integer.MAX_VALUE >>> 1;
        while (i < limit) {
            line = in.readLine();
            if (line == null) {
                break;
            }
            System.out.println(line);
            i++;
        }
    } catch (IOException ex) {
    }
    return Constants.MINT_NULL;
}
Example 7
Project: MyDownload-master  File: Utils.java View source code
public static String getRawData(String string) {
    String dataString = "";
    try {
        URL url;
        url = new URL(string);
        URLConnection conn = url.openConnection();
        // conn.connect();
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        byte buffer[] = new byte[1024];
        String readerString;
        while ((readerString = reader.readLine()) != null) {
            dataString += readerString;
        }
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
        log("IOException", "" + e);
    }
    log("getRawData", dataString);
    return dataString;
}
Example 8
Project: nptornews-master  File: FileUtils.java View source code
public static CharSequence readFile(Resources resources, int id) {
    BufferedReader in = null;
    try {
        in = new BufferedReader(new InputStreamReader(resources.openRawResource(id)), 8192);
        String line;
        StringBuilder buffer = new StringBuilder();
        while ((line = in.readLine()) != null) {
            buffer.append(line).append('\n');
        }
        // Chomp the last newline
        if (buffer.length() > 0) {
            buffer.deleteCharAt(buffer.length() - 1);
        }
        return buffer;
    } catch (IOException e) {
        return "";
    } finally {
        closeStream(in);
    }
}
Example 9
Project: molgenis-master  File: ScriptTest.java View source code
@Test
public void generateScript() throws IOException {
    FileStore fileStore = new FileStore(System.getProperty("java.io.tmpdir"));
    Map<String, Object> parameterValues = Collections.singletonMap("name", "Piet");
    Script script = mock(Script.class);
    when(script.getContent()).thenReturn("Hey ${name}");
    when(script.generateScript(fileStore, "txt", parameterValues)).thenCallRealMethod();
    File f = script.generateScript(fileStore, "txt", parameterValues);
    assertNotNull(f);
    assertTrue(f.exists());
    assertTrue(f.getPath().endsWith(".txt"));
    String s = FileCopyUtils.copyToString(new InputStreamReader(new FileInputStream(f)));
    assertEquals("Hey Piet", s);
    f.delete();
}
Example 10
Project: liferay-ide-master  File: CompareFileHandler.java View source code
protected File getTemplateFile(IFile currentFile) throws Exception {
    final IProject currentProject = currentFile.getProject();
    final IFile bndfile = currentProject.getFile("bnd.bnd");
    File templateFile = null;
    try (final BufferedReader reader = new BufferedReader(new InputStreamReader(bndfile.getContents()))) {
        String fragment;
        while ((fragment = reader.readLine()) != null) {
            if (fragment.startsWith("Fragment-Host:")) {
                fragment = fragment.substring(fragment.indexOf(":") + 1, fragment.indexOf(";")).trim();
                break;
            }
        }
        final String hookfolder = currentFile.getFullPath().toOSString().substring(currentFile.getFullPath().toOSString().lastIndexOf("META-INF"));
        final IPath templateLocation = GradleCore.getDefault().getStateLocation().append(fragment).append(hookfolder);
        templateFile = new File(templateLocation.toOSString());
        if (!templateFile.exists()) {
            throw new FileNotFoundException("Template not found.");
        }
    }
    return templateFile;
}
Example 11
Project: JPaxos-master  File: BarrierClient.java View source code
public void enterBarrier(String host, int port, int requests, long time, int number) {
    try {
        Socket skt = new Socket(host, port);
        // System.out.println("# " + requests + " " + time);
        DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(skt.getOutputStream()));
        dos.writeInt(number);
        dos.writeInt(requests);
        dos.writeLong(time);
        dos.flush();
        BufferedReader in = new BufferedReader(new InputStreamReader(skt.getInputStream()));
        while (!in.ready()) {
        }
        in.readLine();
        in.close();
        dos.close();
        skt.close();
    } catch (Exception e) {
        System.out.print("Whoops! It didn't work!\n");
        System.exit(1);
    }
}
Example 12
Project: trie4j-master  File: GenHtml.java View source code
public static void main(String[] args) throws Exception {
    String templ = null;
    InputStream temps = GenHtml.class.getResourceAsStream("template.txt");
    try {
        templ = StreamUtil.readAsString(temps, "UTF-8");
    } finally {
        temps.close();
    }
    InputStream res = GenHtml.class.getResourceAsStream("result.txt");
    try {
        BufferedReader r = new BufferedReader(new InputStreamReader(res, "UTF-8"));
        String line = null;
        while ((line = r.readLine()) != null) {
            String[] vals = line.split("[ ]+");
            String name = vals[0].substring(0, vals[0].length() - 1).replaceAll("\\(", "\\\\(").replaceAll("\\)", "\\\\)").trim();
            templ = templ.replaceAll("\\$\\{" + name + "\\.build\\}", String.format("%,d", Integer.valueOf(vals[1].replace(',', ' ').trim()))).replaceAll("\\$\\{" + name + "\\.contains\\}", String.format("%,d", Integer.valueOf(vals[2].replace(',', ' ').trim()))).replaceAll("\\$\\{" + name + "\\.mem\\}", String.format("%.1f", Integer.valueOf(vals[3].replace(',', ' ').trim()) / 1000000.0));
        }
        System.out.println(templ);
    } finally {
        res.close();
    }
}
Example 13
Project: vlc-android-macbuild-master  File: StreamHelper.java View source code
public static String readStreamLineByLine(InputStream inputStream) {
    InputStreamReader reader = new InputStreamReader(inputStream);
    BufferedReader buffReader = new BufferedReader(reader);
    StringBuilder text = new StringBuilder();
    String resultText = null;
    try {
        String line;
        while ((line = buffReader.readLine()) != null) {
            text.append(line);
            text.append('\n');
        }
        resultText = text.toString();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            buffReader.close();
            reader.close();
        } catch (Exception e) {
        }
    }
    return resultText;
}
Example 14
Project: SecurePhoto-master  File: SecurePhotoBaseTests.java View source code
@Test(timeout = 10000)
public void testServerConnectivity() throws Exception {
    Socket clientSocket = null;
    PrintWriter outWriter = null;
    BufferedReader inReader = null;
    String response = null;
    try {
        clientSocket = new Socket("localhost", SPConstants.SERVER_DEFAULT_PORT);
        outWriter = new PrintWriter(clientSocket.getOutputStream(), true);
        inReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        outWriter.println("Testing connectivity");
        response = inReader.readLine();
    } catch (IOException e) {
        throw new Exception("Exception during writing to socket: " + e.getMessage());
    }
    Assert.assertEquals(SPConstants.SERVER_OK_MESSAGE, response);
}
Example 15
Project: tmdm-studio-se-master  File: TestUtil.java View source code
/**
     * Used to read test resource
     * 
     * @param fileName
     * @return
     * @throws Exception
     */
public static String readTestResource(Class cls, String fileName) throws Exception {
    InputStreamReader fr = null;
    BufferedReader br = null;
    try {
        InputStream inputStream = cls.getResourceAsStream(fileName);
        fr = new InputStreamReader(inputStream);
        br = new BufferedReader(fr);
        StringBuffer buffer = new StringBuffer();
        String tmpStr;
        while ((tmpStr = br.readLine()) != null) {
            buffer.append(tmpStr);
        }
        return buffer.toString();
    } finally {
        if (br != null) {
            br.close();
        }
        if (fr != null) {
            fr.close();
        }
    }
}
Example 16
Project: polly-master  File: UTF8Control.java View source code
public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload) throws IllegalAccessException, InstantiationException, IOException {
    // The below is a copy of the default implementation.
    final String bundleName = toBundleName(baseName, locale);
    //$NON-NLS-1$
    final String resourceName = toResourceName(bundleName, "properties");
    ResourceBundle bundle = null;
    InputStream stream = null;
    if (reload) {
        URL url = loader.getResource(resourceName);
        if (url != null) {
            URLConnection connection = url.openConnection();
            if (connection != null) {
                connection.setUseCaches(false);
                stream = connection.getInputStream();
            }
        }
    } else {
        stream = loader.getResourceAsStream(resourceName);
    }
    if (stream != null) {
        try {
            // Only this line is changed to make it to read properties files as UTF-8.
            bundle = new PropertyResourceBundle(//$NON-NLS-1$
            new InputStreamReader(stream, "UTF-8"));
        } finally {
            stream.close();
        }
    }
    return bundle;
}
Example 17
Project: ldbc_snb_datagen-master  File: EmpiricalDistribution.java View source code
@Override
public ArrayList<Bucket> getBuckets(Configuration conf) {
    fileName = conf.get("ldbc.snb.datagen.generator.distribution.EmpiricalDistribution.fileName");
    ArrayList<Pair<Integer, Integer>> histogram = new ArrayList<Pair<Integer, Integer>>();
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(fileName), "UTF-8"));
        String line;
        while ((line = reader.readLine()) != null) {
            String data[] = line.split(" ");
            histogram.add(new Pair<Integer, Integer>(Integer.parseInt(data[0]), Integer.parseInt(data[1])));
        }
        reader.close();
        return Bucket.bucketizeHistogram(histogram, 1000);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
Example 18
Project: many-ql-master  File: CommandLine.java View source code
/**
	 * The main method, which gets executed once this class is run. Enabled the user
	 * to enter a string, which is then parsed and shown as an AST.
	 */
public static void main(String[] args) {
    ErrorEnvironment errorEnvironment = new ErrorEnvironment();
    try {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Press 'x' to stop");
        while (true) {
            System.out.print("Enter a statement:");
            String str = br.readLine();
            if ("x".equalsIgnoreCase(str)) {
                System.out.println("Stopped.");
                break;
            } else {
                QLNode tree = Parser.parse(str);
                if (tree instanceof Statement) {
                    errorEnvironment = TypeChecker.check((Statement) tree, null);
                    PrettyPrinter.print((Statement) tree, new ConsolePrinter());
                }
                if (errorEnvironment.hasErrors()) {
                    System.out.println(errorEnvironment.getErrors());
                    continue;
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Example 19
Project: couchbase-lite-android-ektorp-master  File: Attachments.java View source code
public void testAttachments() throws IOException {
    HttpClient httpClient = new CBLiteHttpClient(manager);
    CouchDbInstance dbInstance = new StdCouchDbInstance(httpClient);
    CouchDbConnector dbConnector = dbInstance.createConnector(DEFAULT_TEST_DB, true);
    TestObject test = new TestObject(1, false, "ektorp");
    //create a document
    dbConnector.create(test);
    //attach file to it
    byte[] attach1 = "This is the body of attach1".getBytes();
    ByteArrayInputStream b = new ByteArrayInputStream(attach1);
    AttachmentInputStream a = new AttachmentInputStream("attach", b, "text/plain");
    dbConnector.createAttachment(test.getId(), test.getRevision(), a);
    AttachmentInputStream readAttachment = dbConnector.getAttachment(test.getId(), "attach");
    Assert.assertEquals("text/plain", readAttachment.getContentType());
    Assert.assertEquals("attach", readAttachment.getId());
    BufferedReader br = new BufferedReader(new InputStreamReader(readAttachment));
    Assert.assertEquals("This is the body of attach1", br.readLine());
}
Example 20
Project: core-android-master  File: StreamGobbler.java View source code
public void run() {
    try {
        PrintWriter pw = null;
        if (os != null)
            pw = new PrintWriter(os);
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String line = null;
        while ((line = br.readLine()) != null) {
            if (pw != null)
                pw.println(line);
            if (Cfg.DEBUG) {
                Check.log(TAG + " (run): " + type + ">" + line);
            }
        }
        if (pw != null)
            pw.flush();
    } catch (IOException ioe) {
        if (Cfg.DEBUG) {
            Check.log(TAG + " (run) Error: " + ioe);
        }
    }
}
Example 21
Project: snap-desktop-master  File: ImportTrackActionTest.java View source code
@Test
public void testReadTrack() throws Exception {
    CrsGeoCoding geoCoding = new CrsGeoCoding(DefaultGeographicCRS.WGS84, new Rectangle(360, 180), new AffineTransform());
    InputStreamReader reader = new InputStreamReader(getClass().getResourceAsStream("TrackData.csv"));
    FeatureCollection<SimpleFeatureType, SimpleFeature> featureCollection = ImportTrackAction.readTrack(reader, geoCoding);
    assertNotNull(featureCollection);
    assertEquals(23, featureCollection.size());
    // test ordering
    SimpleFeature[] simpleFeatures = featureCollection.toArray(new SimpleFeature[0]);
    assertEquals(23, simpleFeatures.length);
    assertEquals("ID00000000", simpleFeatures[0].getID());
    assertEquals("ID00000011", simpleFeatures[11].getID());
    assertEquals("ID00000022", simpleFeatures[22].getID());
}
Example 22
Project: andlytics-master  File: DataLoader.java View source code
/**
	 * reads the changelog file and returns its content as a String.
	 * 
	 * @param context
	 *            the context.
	 * @param ressourceName
	 *            Name of the ressource to be loaded
	 * @return content of the ressource as a String.
	 * @throws IOException
	 *             if errors occur while reading the changelog file
	 */
public static String loadData(final Context context, final String ressourceName) throws IOException {
    int resourceIdentifier = context.getApplicationContext().getResources().getIdentifier(ressourceName, "raw", context.getApplicationContext().getPackageName());
    if (resourceIdentifier != 0) {
        InputStream inputStream = context.getApplicationContext().getResources().openRawResource(resourceIdentifier);
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        String line;
        StringBuffer data = new StringBuffer();
        while ((line = reader.readLine()) != null) {
            data.append(line);
        }
        reader.close();
        return data.toString();
    }
    return null;
}
Example 23
Project: cms-ce-master  File: TranslationReaderTest.java View source code
@Test
public void testTranslate() throws Exception {
    Map<String, String> translations = new HashMap<String, String>();
    translations.put("%__example__%", "alert");
    final String xslFilename = getClass().getName().replace('.', '/') + ".xsl";
    final InputStream xslInputStream = getClass().getClassLoader().getResourceAsStream(xslFilename);
    final Reader reader = new InputStreamReader(xslInputStream, Charset.forName("UTF-8"));
    final TranslationReader translationReader = new TranslationReader(translations, reader);
    final int length = xslInputStream.available();
    final char[] xslBuffer = new char[length];
    translationReader.read(xslBuffer, 0, length);
    final String xslString = new String(xslBuffer);
    assertFalse("The XSL contains untranslated string", xslString.contains("%__example__%"));
}
Example 24
Project: cbe-master  File: FileLoader.java View source code
public List<String> loadLines(String filename) {
    BufferedReader bufferedReader = null;
    InputStream inputStream = null;
    InputStreamReader inputStreamReader = null;
    List<String> lines = new ArrayList<String>();
    try {
        inputStream = getClass().getClassLoader().getResourceAsStream(filename);
        inputStreamReader = new InputStreamReader(inputStream);
        bufferedReader = new BufferedReader(inputStreamReader);
        String line = null;
        while ((line = bufferedReader.readLine()) != null) lines.add(line);
        inputStream.close();
        inputStreamReader.close();
        bufferedReader.close();
    } catch (IOException e) {
        System.err.println("Failed to read and/or close file:");
        e.printStackTrace();
    }
    return lines;
}
Example 25
Project: quickml-master  File: InstanceLoader.java View source code
public static List<ClassifierInstance> getAdvertisingInstances() {
    CSVToInstanceReader csvToInstanceReader = new CSVToInstanceReaderBuilder().collumnNameForLabel("outcome").buildCsvReader();
    List<ClassifierInstance> advertisingInstances;
    try {
        final BufferedReader br = new BufferedReader(new InputStreamReader((new GZIPInputStream(InstanceLoader.class.getResourceAsStream("advertisingData.csv.gz")))));
        advertisingInstances = csvToInstanceReader.readCsvFromReader(br);
    } catch (Exception e) {
        logger.error("failed to get advertising instances", e);
        throw new RuntimeException("failed to get advertising instances");
    }
    return advertisingInstances;
}