java学习第二十一天
1.inputstream(字节输入流)
java中的inputstream是一个面向字节的流抽象类,其依据详细应用派生出各种详细的类。
比方FileInputStream就是继承于InputStream,专门用来读取文件流的对象
package com.itbuluoge.test;
import java.io.FileInputStream;
public class ByteInputFile {
public static String read() throws Exception
{
FileInputStream fit=new FileInputStream("test.txt");
int c;
String sb="";
while((c=fit.read())!=-1)
{
sb+=(char)c;
}
return sb;
}
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
System.out.println(read());
}
}
输出结果
2.reader
FileReader类从InputStreamReader类继承而来
import java.io.*;
public class FileRead {
public static void main(String args[]) throws IOException {
File file = new File("Hello1.txt");
// 创建文件
file.createNewFile();
// creates a FileWriter Object
FileWriter writer = new FileWriter(file);
// 向文件写入内容
writer.write("This\n is\n an\n example\n");
writer.flush();
writer.close();
// 创建 FileReader 对象
FileReader fr = new FileReader(file);
char[] a = new char[50];
fr.read(a); // 读取数组中的内容
for (char c : a)
System.out.print(c); // 一个一个打印字符
fr.close();
}
}
3.writer
FileWriter 类从 OutputStreamWriter 类继承而来
import java.io.*;
public class FileRead {
public static void main(String args[]) throws IOException {
File file = new File("Hello1.txt");
// 创建文件
file.createNewFile();
// creates a FileWriter Object
FileWriter writer = new FileWriter(file);
// 向文件写入内容
writer.write("This\n is\n an\n example\n");
writer.flush();
writer.close();
// 创建 FileReader 对象
FileReader fr = new FileReader(file);
char[] a = new char[50];
fr.read(a); // 从数组中读取内容
for (char c : a)
System.out.print(c); // 一个个打印字符
fr.close();
}
}