Java by API/java.io/InputStreamReader

Материал из Java эксперт
Перейти к: навигация, поиск

InputStreamReader: close()

 

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class Main {
  public static void main(String[] args) {
    try {
      char[] chars = new char[2];
      chars[0] = "\u4F60";
      chars[1] = "\u597D";
      String encoding = "GB18030";
      File textFile = new File("C:\\temp\\myFile.txt");
      PrintWriter writer = new PrintWriter(textFile,encoding);
      writer.write(chars);
      writer.close();
      // read back
      InputStreamReader reader = new InputStreamReader(new FileInputStream(textFile), encoding);
      char[] chars2 = new char[2];
      reader.read(chars2);
      System.out.print(chars2[0]);
      System.out.print(chars2[1]);
      reader.close();
    } catch (IOException e) {
      System.out.println(e.toString());
    }
  }
}





new InputStreamReader(InputStream in)

 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class MainClass {
  public static void main(String args[]) {
    try {
      System.out.print("Enter your name: ");
      InputStreamReader reader = new InputStreamReader(System.in);
      BufferedReader in = new BufferedReader(reader);
      String name = in.readLine();
      System.out.println("Hello, " + name + ". Enter three ints...");
      int[] values = new int[3];
      double sum = 0.0;
      for (int i = 0; i < values.length; i++) {
        System.out.print("Number " + (i + 1) + ": ");
        String temp = in.readLine();
        values[i] = Integer.parseInt(temp);
        sum += values[i];
      }
      System.out.println("The average equals " + sum / values.length);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}





new InputStreamReader(InputStream in, String charsetName)

 
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class MainClass {
  public static void Converter(String input, String output) {
    try {
      FileInputStream fis = new FileInputStream(new File(input));
      BufferedReader in = new BufferedReader(new InputStreamReader(fis, "SJIS"));
      FileOutputStream fos = new FileOutputStream(new File(output));
      BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fos, "UTF8"));
      int len = 80;
      char buf[] = new char[len];
      int numRead;
      while ((numRead = in.read(buf, 0, len)) != -1)
        out.write(buf, 0, numRead);
      out.close();
      in.close();
    } catch (IOException e) {
      System.out.println("An I/O Exception Occurred: " + e);
    }
  }
  public static void main(String args[]) {
    MainClass.Converter(args[0], args[1]);
  }
}