Java Tutorial/File/StringReader

Материал из Java эксперт
Версия от 17:44, 31 мая 2010; (обсуждение)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Create BufferedReader from StringReader

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.EOFException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
public class MainClass {
  public static void main(String[] args) throws IOException {
    try {
      BufferedReader in4 = new BufferedReader(new StringReader("asdf"));
      PrintWriter out1 = new PrintWriter(new BufferedWriter(new FileWriter("IODemo.out")));
      int lineCount = 1;
      String s = null;
      while((s = in4.readLine()) != null )
        out1.println(lineCount++ + ": " + s);
      out1.close();
    } catch(EOFException e) {
      System.err.println("End of stream");
    }
  }
}





Create StringReader from a string

import java.io.IOException;
import java.io.StringReader;
public class MainClass {
  public static void main(String[] args) throws IOException {

    StringReader in2 = new StringReader("a bc ddd");
    int c;
    while ((c = in2.read()) != -1)
      System.out.print((char) c);
  }
}//



a bc ddd


Using the StringReader class

import java.io.StreamTokenizer;
import java.io.StringReader;
public class Main {
  public static void main(String[] args) throws Exception{
    StringReader reader = new StringReader("this is a test");
    int wordCount = 0;
    StreamTokenizer streamTokenizer = new StreamTokenizer(reader);
    while (streamTokenizer.nextToken() != StreamTokenizer.TT_EOF) {
      if (streamTokenizer.ttype == StreamTokenizer.TT_WORD)
        wordCount++;
    }
    System.out.println("Number of words in file: " + wordCount);
  }
}
//Number of words in file: 4