package test; import java.io.*; /** * 读取一个文件,并打印在控制台上。 */ class FileReaderTest { public static void main(String[] args) throws IOException { FileReader fr = new FileReader("d:ss.txt"); char[] buf = new char[1024]; int num; while ((num = fr.read(buf)) != -1) { System.out.println(new String(buf)); System.out.print(new String(buf, 0, num)); } fr.close(); } } class FileReaderDemo2 { public static void main(String[] args) throws IOException { //注意下面读的文件内部只写入"abcf"内容来测试边界问题。 FileReader fr = new FileReader("d:ss.txt"); //定义一个字符数组。用于存储读到字符。 //该read(char[])返回的是读到字符个数。 char[] buf = new char[1]; int num1 = fr.read(buf); System.out.println("num1=" + num1 + " " + new String(buf)); int num2 = fr.read(buf); System.out.println("num2=" + num2 + " " + new String(buf, 0, num2)); int num3 = fr.read(buf); System.out.println("num3=" + num3 + " " + new String(buf, 0, num3)); fr.close(); } } class FileReaderDemo3 { public static void main(String[] args) throws IOException { File f1 = new File("d:ss.txt"); InputStreamReader read = new InputStreamReader(new FileInputStream(f1), "UTF-8"); BufferedReader reader = new BufferedReader(read); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } } class FileReaderDemo4 { public static void main(String[] args) throws IOException { File f1 = new File("d:ss.txt"); InputStreamReader read = new InputStreamReader(new FileInputStream(f1), "UTF-8"); int num; char[] chars = new char[1024]; while ((num = read.read(chars)) != -1) { System.out.println(chars); System.out.println(new String(chars, 0, num)); } } }