无论哪种面向对象的语言,对流的认识和对文件IO的操作都是经常需要用到的知识,所以一起上车走一遭吧。
(一)流概念,流,简单来说一个流可以理解为一个数据的序列。输入流表示从一个源读取数据,输出流表示向一个目标写数据。详细的数据流的介绍可自行百度。
java中基本的流分为输入流,输出流,io流再细分为字节流,字符流。
盗图一张:
上学的时候最迷的就是输入流和输出流,傻傻分不清楚,其实这里的输入输出讲的是可以这样理解
输入流:数据从文件向流输入 (其实流输入可能更好理解) 输出流 : 数据从流输出到文件(流输出)
你也可以理解为,流是公交车,输入流是上车,输出流是下车,滴滴,老司机发车了哈哈。
首先流输入:
/**读取多个字符*/
public static void readChar() throws IOException{
char c;
// 使用 System.in 创建 BufferedReader
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("输入字符, 按下 'q' 键退出。");
// 读取字符
do {
c = (char) br.read();
System.out.println(c);
} while(c != 'q');
}
/**读取字符串*/
public static void readLine() throws IOException{
// 使用 System.in 创建 BufferedReader
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String str;
System.out.println("请输入一行字符串");
System.out.println("输入'end'结束");
do {
str = br.readLine();
System.out.println(str);
} while(!str.equals("end"));
}
然后流输出:
/**控制台输出 */
public static void outputStream() throws IOException{
String write;
write = "大吉大利今晚吃鸡";
System.out.write(write.getBytes());
System.out.write('\n');
}
(二)读写文件
FileInputStream
该流用于从文件读取数据,它的对象可以用关键字 new 来创建。
有多种构造方法可用来创建对象。
可以使用字符串类型的文件名来创建一个输入流对象来读取文件:
/**文件输入流
* @throws IOException */
public static void fileInputStream() throws IOException{
//新建输入流对象并将text.xls中的数据输入流中
FileInputStream fileInputStream = new FileInputStream("D:/新建文本文档.txt");
int size = fileInputStream.available();
for(int i=0; i< size; i++){
System.out.print((char)fileInputStream.read() + " ");
}
fileInputStream.close();
}
也可以使用一个文件对象来创建一个输入流对象来读取文件。我们首先得使用 File() 方法来创建一个文件对象:
/**文件输出流
* @throws IOException */
public static void fileOutputStream() throws IOException{
File file = new File("D:fileOutPut.txt");
@SuppressWarnings("resource")
//新建输出流对象并且制定输出到文件fileOutPut.txt中
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write("吃不吃鸡".getBytes());
fileOutputStream.close();
}
要注意的是流使用完之后一定要关闭。