Java Code Examples for java.io.FileReader#read()

The following examples show how to use java.io.FileReader#read() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestSources.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
static String accessTestData(String testprefix, String basename, TestPart part) throws Exception {

    String fname = testprefix + File.separator + basename + partext(part);

    String result = null;
    try {
      File f = new File(fname);
      if (!f.canRead())
        return null;
      FileReader fr = new FileReader(fname);
      StringBuffer cbuf = new StringBuffer();
      int c;
      while ((c = fr.read()) != -1) {
        cbuf.append((char) c);
      }
      return cbuf.toString();
    } catch (Exception e) {
      System.err.println("File io failure: " + e.toString());
      e.printStackTrace();
      throw e;
    }

  }
 
Example 2
Source File: Scanner.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 *
 **/
void readFile (IncludeEntry file, String filename) throws IOException
{
  data.fileEntry = file;
  data.filename = filename;
  // <f49747.1>
  //FileInputStream stream = new FileInputStream (data.filename);
  //data.fileBytes = new byte [stream.available ()];
  //stream.read (data.fileBytes);
  //stream.close (); <ajb>
  File idlFile = new File (data.filename);
  int len = (int)idlFile.length ();
  FileReader fileReader = new FileReader (idlFile);
  // <d41679> data.fileBytes = new char [len];
  final String EOL = System.getProperty ("line.separator");
  data.fileBytes = new char [len + EOL.length ()];

  fileReader.read (data.fileBytes, 0, len);
  fileReader.close ();

  // <d41679>
  for (int i = 0; i < EOL.length (); i++)
    data.fileBytes[len + i] = EOL.charAt (i);

  readChar ();
}
 
Example 3
Source File: Analyzer.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/** Loads the file and performs conversion of line separators to LF.
* This method can be used in debuging of syntax scanner or somewhere else.
* @param fileName the name of the file to load
* @return array of loaded characters with '\n' as line separator
*/

public static char[] loadFile(String fileName) throws IOException {
    File file = new File(fileName);
    char chars[] = new char[(int)file.length()];
    FileReader reader = new FileReader(file);
    reader.read(chars);
    reader.close();
    int len = Analyzer.convertLSToLF(chars, chars.length);
    if (len != chars.length) {
        char copyChars[] = new char[len];
        System.arraycopy(chars, 0, copyChars, 0, len);
        chars = copyChars;
    }
    return chars;
}
 
Example 4
Source File: JavaFlyTokensTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void test() throws Exception {
    File testJComponentFile = new File(getDataDir() + "/testfiles/JComponent.java.txt");
    FileReader r = new FileReader(testJComponentFile);
    int fileLen = (int)testJComponentFile.length();
    CharBuffer cb = CharBuffer.allocate(fileLen);
    r.read(cb);
    cb.rewind();
    String text = cb.toString();
    TokenHierarchy<?> hi = TokenHierarchy.create(text, JavaTokenId.language());
    TokenSequence<?> ts = hi.tokenSequence();
    
    System.err.println("Flyweight tokens: " + LexerTestUtilities.flyweightTokenCount(ts)
            + "\nTotal tokens: " + ts.tokenCount()
            + "\nFlyweight text length: " + LexerTestUtilities.flyweightTextLength(ts)
            + "\nTotal text length: " + fileLen
            + "\nDistribution: " + LexerTestUtilities.flyweightDistribution(ts)
    );

    assertEquals(LexerTestUtilities.flyweightTokenCount(ts), 13786);
    assertEquals(LexerTestUtilities.flyweightTextLength(ts), 21710);
    assertEquals(ts.tokenCount(), 21379);
    
}
 
Example 5
Source File: RefactoringTestCase.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
protected void tearDown() throws Exception {
    getRef().flush();
    getRef().close();
    assertFile("Golden file differs ", getReferencFile(), getGoldenFile(), getWorkDir(), new LineDiff());
    //compareReferenceFiles();
    File diffFile = getDiffFile(getReferencFile().getAbsolutePath(), getWorkDir());
    System.out.println("+++++++++ Diff file ["+diffFile.getAbsolutePath()+"] exists=" + diffFile.exists());
    if (diffFile.exists()) {
        System.out.println("============= DIFF >>>> =======================================");
        FileReader fr = new FileReader(diffFile);
        int oneByte;
        while ((oneByte = fr.read()) != -1) {
            System.out.print((char) oneByte);
        }
        System.out.flush();
        System.out.println("============= <<<< DIFF =======================================");
    }

    System.out.println("Test " + getName() + " finished !");
}
 
Example 6
Source File: Solution.java    From JavaRushTasks with MIT License 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    String alphabetL = "abcdefghijklmnopqrstuvwxyz";
    String alphabetH = alphabetL.toUpperCase();

    FileReader f = new FileReader(args[0]);

    int count = 0;
    while (f.ready()) {
        char s = (char) f.read();
        if ((alphabetL.indexOf(s) > -1) || alphabetH.indexOf(s) > -1)
            count++;
    }
    f.close();

    System.out.println(count);

}
 
Example 7
Source File: Scanner.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 *
 **/
void readFile (IncludeEntry file, String filename) throws IOException
{
  data.fileEntry = file;
  data.filename = filename;
  // <f49747.1>
  //FileInputStream stream = new FileInputStream (data.filename);
  //data.fileBytes = new byte [stream.available ()];
  //stream.read (data.fileBytes);
  //stream.close (); <ajb>
  File idlFile = new File (data.filename);
  int len = (int)idlFile.length ();
  FileReader fileReader = new FileReader (idlFile);
  // <d41679> data.fileBytes = new char [len];
  final String EOL = System.getProperty ("line.separator");
  data.fileBytes = new char [len + EOL.length ()];

  fileReader.read (data.fileBytes, 0, len);
  fileReader.close ();

  // <d41679>
  for (int i = 0; i < EOL.length (); i++)
    data.fileBytes[len + i] = EOL.charAt (i);

  readChar ();
}
 
Example 8
Source File: Scanner.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/**
 *
 **/
void readFile (IncludeEntry file, String filename) throws IOException
{
  data.fileEntry = file;
  data.filename = filename;
  // <f49747.1>
  //FileInputStream stream = new FileInputStream (data.filename);
  //data.fileBytes = new byte [stream.available ()];
  //stream.read (data.fileBytes);
  //stream.close (); <ajb>
  File idlFile = new File (data.filename);
  int len = (int)idlFile.length ();
  FileReader fileReader = new FileReader (idlFile);
  // <d41679> data.fileBytes = new char [len];
  final String EOL = System.getProperty ("line.separator");
  data.fileBytes = new char [len + EOL.length ()];

  fileReader.read (data.fileBytes, 0, len);
  fileReader.close ();

  // <d41679>
  for (int i = 0; i < EOL.length (); i++)
    data.fileBytes[len + i] = EOL.charAt (i);

  readChar ();
}
 
Example 9
Source File: Scanner.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 *
 **/
void readFile (IncludeEntry file, String filename) throws IOException
{
  data.fileEntry = file;
  data.filename = filename;
  // <f49747.1>
  //FileInputStream stream = new FileInputStream (data.filename);
  //data.fileBytes = new byte [stream.available ()];
  //stream.read (data.fileBytes);
  //stream.close (); <ajb>
  File idlFile = new File (data.filename);
  int len = (int)idlFile.length ();
  FileReader fileReader = new FileReader (idlFile);
  // <d41679> data.fileBytes = new char [len];
  final String EOL = System.getProperty ("line.separator");
  data.fileBytes = new char [len + EOL.length ()];

  fileReader.read (data.fileBytes, 0, len);
  fileReader.close ();

  // <d41679>
  for (int i = 0; i < EOL.length (); i++)
    data.fileBytes[len + i] = EOL.charAt (i);

  readChar ();
}
 
Example 10
Source File: TestFiles.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
static String accessTestData(String testprefix, String basename, TestPart part) throws Exception {
  String fname = testprefix + "/" + basename + partext(part);

  String result = null;
  try {
    File f = new File(fname);
    if (!f.canRead())
      return null;
    FileReader fr = new FileReader(fname);
    StringBuffer cbuf = new StringBuffer();
    int c;
    while ((c = fr.read()) != -1) {
      cbuf.append((char) c);
    }
    return cbuf.toString();
  } catch (Exception e) {
    System.err.println("File io failure: " + e.toString());
    e.printStackTrace();
    throw e;
  }

}
 
Example 11
Source File: DDTestRunner.java    From marathonv5 with Apache License 2.0 5 votes vote down vote up
private String getScript(File file) throws IOException {
    int size = (int) file.length();
    char[] cs = new char[size + 64];
    FileReader fileReader = new FileReader(file);
    int n = fileReader.read(cs);
    fileReader.close();
    return new String(cs, 0, n);
}
 
Example 12
Source File: JavaLexerPerformanceTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private String readJComponentFile() throws Exception {
    File testJComponentFile = new File(getDataDir() + "/testfiles/JComponent.java.txt");
    FileReader r = new FileReader(testJComponentFile);
    try {
        int fileLen = (int)testJComponentFile.length();
        CharBuffer cb = CharBuffer.allocate(fileLen);
        r.read(cb);
        cb.rewind();
        return cb.toString();
    } finally {
        r.close();
    }
}
 
Example 13
Source File: OperationStepUtil.java    From SoloPi with Apache License 2.0 5 votes vote down vote up
/**
 * load steps
 * @param logBean
 */
private static void loadCases(GeneralOperationLogBean logBean) {
    if (logBean == null) {
        return;
    }

    // if stored in path
    String path = logBean.getStorePath();
    if (!StringUtil.isEmpty(path)) {
        LogUtil.i(TAG, "Should load case from " + path);
        File f = new File(path);
        if (f.exists()) {
            try {
                FileReader reader = new FileReader(f);
                StringBuilder sb = new StringBuilder();
                char[] content = new char[8192];
                int count;
                while ((count = reader.read(content)) > 0) {
                    sb.append(content, 0, count);
                }
                List<OperationStep> steps = JSON.parseArray(sb.toString(), OperationStep.class);
                logBean.setSteps(steps);
            } catch (IOException e) {
                LogUtil.e(TAG, "Throw IOException: " + e.getMessage(), e);
            }
        }
    }
}
 
Example 14
Source File: TokenDumpCheck.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static String readFile(NbTestCase test, File f) throws Exception {
    FileReader r = new FileReader(f);
    int fileLen = (int)f.length();
    CharBuffer cb = CharBuffer.allocate(fileLen);
    r.read(cb);
    cb.rewind();
    return cb.toString();
}
 
Example 15
Source File: TestHardLink.java    From hadoop with Apache License 2.0 5 votes vote down vote up
private String fetchFileContents(File file) 
throws IOException {
  char[] buf = new char[20];
  FileReader fr = new FileReader(file);
  int cnt = fr.read(buf); 
  fr.close();
  char[] result = Arrays.copyOf(buf, cnt);
  return new String(result);
}
 
Example 16
Source File: Solution.java    From JavaRushTasks with MIT License 4 votes vote down vote up
public static void main(String[] args) throws IOException {

        FileReader f = new FileReader(args[0]);

        int spaceCount = 0;
        int charCount = 0;
        while (f.ready()) {
            char ch = (char) f.read();
            charCount++;

            if (ch == ' ')
                spaceCount++;

        }

        f.close();

        System.out.println(String.format("%.2f", ((float) spaceCount / charCount) * 100));


    }
 
Example 17
Source File: TestNativeIO.java    From hadoop with Apache License 2.0 4 votes vote down vote up
@Test (timeout = 30000)
public void testSetFilePointer() throws Exception {
  if (!Path.WINDOWS) {
    return;
  }

  LOG.info("Set a file pointer on Windows");
  try {
    File testfile = new File(TEST_DIR, "testSetFilePointer");
    assertTrue("Create test subject",
        testfile.exists() || testfile.createNewFile());
    FileWriter writer = new FileWriter(testfile);
    try {
      for (int i = 0; i < 200; i++)
        if (i < 100)
          writer.write('a');
        else
          writer.write('b');
      writer.flush();
    } catch (Exception writerException) {
      fail("Got unexpected exception: " + writerException.getMessage());
    } finally {
      writer.close();
    }

    FileDescriptor fd = NativeIO.Windows.createFile(
        testfile.getCanonicalPath(),
        NativeIO.Windows.GENERIC_READ,
        NativeIO.Windows.FILE_SHARE_READ |
        NativeIO.Windows.FILE_SHARE_WRITE |
        NativeIO.Windows.FILE_SHARE_DELETE,
        NativeIO.Windows.OPEN_EXISTING);
    NativeIO.Windows.setFilePointer(fd, 120, NativeIO.Windows.FILE_BEGIN);
    FileReader reader = new FileReader(fd);
    try {
      int c = reader.read();
      assertTrue("Unexpected character: " + c, c == 'b');
    } catch (Exception readerException) {
      fail("Got unexpected exception: " + readerException.getMessage());
    } finally {
      reader.close();
    }
  } catch (Exception e) {
    fail("Got unexpected exception: " + e.getMessage());
  }
}
 
Example 18
Source File: CR6401137Test.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Test
public final void testTransform() {

    try {
        String str = new String();
        ByteArrayOutputStream byte_stream = new ByteArrayOutputStream();
        File inputFile = new File(getClass().getResource("CR6401137.xml").getPath());
        FileReader in = new FileReader(inputFile);
        int c;

        while ((c = in.read()) != -1) {
            str = str + new Character((char) c).toString();
        }

        in.close();

        System.out.println(str);
        byte buf[] = str.getBytes();
        byte_stream.write(buf);
        String style_sheet_uri = "CR6401137.xsl";
        byte[] xml_byte_array = byte_stream.toByteArray();
        InputStream xml_input_stream = new ByteArrayInputStream(xml_byte_array);

        Source xml_source = new StreamSource(xml_input_stream);

        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer = tFactory.newTransformer();
        StreamSource source = new StreamSource(getClass().getResourceAsStream(style_sheet_uri));
        transformer = tFactory.newTransformer(source);

        ByteArrayOutputStream result_output_stream = new ByteArrayOutputStream();
        Result result = new StreamResult(result_output_stream);
        transformer.transform(xml_source, result);
        result_output_stream.close();

        // expected success
    } catch (Exception e) {
        // unexpected failure
        e.printStackTrace();
        Assert.fail(e.toString());
    }
}
 
Example 19
Source File: BugDB12665704Test.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Test
public final void testTransform() {

    try {
        String str = new String();
        ByteArrayOutputStream byte_stream = new ByteArrayOutputStream();
        File inputFile = new File(getClass().getResource("BugDB12665704.xml").getPath());
        FileReader in = new FileReader(inputFile);
        int c;

        while ((c = in.read()) != -1) {
            str = str + new Character((char) c).toString();
        }

        in.close();

        System.out.println(str);
        byte buf[] = str.getBytes();
        byte_stream.write(buf);
        String style_sheet_uri = "BugDB12665704.xsl";
        byte[] xml_byte_array = byte_stream.toByteArray();
        InputStream xml_input_stream = new ByteArrayInputStream(xml_byte_array);

        Source xml_source = new StreamSource(xml_input_stream);

        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer = tFactory.newTransformer();
        StreamSource source = new StreamSource(getClass().getResource(style_sheet_uri).toString());
        transformer = tFactory.newTransformer(source);

        ByteArrayOutputStream result_output_stream = new ByteArrayOutputStream();
        Result result = new StreamResult(result_output_stream);
        transformer.transform(xml_source, result);
        result_output_stream.close();

        // expected success
    } catch (Exception e) {
        // unexpected failure
        e.printStackTrace();
        Assert.fail(e.toString());
    }
}
 
Example 20
Source File: PerlJobRunner.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
private File createTempContextScriptFile(File contextScriptFile, Map parameters) throws Exception {
	FileReader reader = new FileReader(contextScriptFile);
	StringBuffer filebuff = new StringBuffer();
	char[] buffer = new char[1024];
	int len;
	while ((len = reader.read(buffer)) >= 0) {
		filebuff.append(buffer, 0, len);
	}
	reader.close();
	Set entries = parameters.entrySet();
	Iterator it = entries.iterator();
	while (it.hasNext()) {
		Map.Entry entry = (Map.Entry) it.next();
		String parameterName = entry.getKey().toString();
		Object parameterValueObj = entry.getValue(); 
		logger.debug("Found parameter '" + parameterName + "' with value '" + parameterValueObj + "'.");
		if (parameterValueObj == null || parameterValueObj.toString().trim().equals("")) {
			logger.debug("Parameter '" + parameterName + "' has no value.");
			continue;
		}
		String parameterValue = parameterValueObj.toString();
		int index = filebuff.indexOf("$_context{" + parameterName + "}");
		if (index < 0) {
			logger.error("Parameter '" + parameterName + "' not found in context script file.");
			continue;
		} else {
			int startIndex = filebuff.indexOf("=", index) + 1;
			int endIndex = filebuff.indexOf(";", startIndex);
			filebuff.replace(startIndex, endIndex, parameterValue);
		}
	}
    String contextScriptFilePath = contextScriptFile.getAbsolutePath();
    String contextScriptDirPath = contextScriptFilePath.substring(0, 
    		contextScriptFilePath.lastIndexOf(File.separatorChar));
    String tempDirPath = contextScriptDirPath + File.separatorChar 
    						+ ".." + File.separatorChar + ".." + File.separatorChar + "temp";
    File tempDir = new File(tempDirPath);
    if (!tempDir.exists()) tempDir.mkdir();
    else {
    	if (!tempDir.isDirectory()) tempDir.delete();
    }
    UUIDGenerator uuidGenerator = UUIDGenerator.getInstance();
    String tempFileName = uuidGenerator.generateTimeBasedUUID().toString();
    TalendEngineConfig config = TalendEngineConfig.getInstance();
    File contextScriptTempFile = new File(tempDirPath + File.separatorChar + tempFileName + config.getPerlExt());
	FileOutputStream fos = new FileOutputStream(contextScriptTempFile);
	fos.write(filebuff.toString().getBytes());
	fos.flush();
	fos.close();
	return contextScriptTempFile;
}