学习java的时候,我们经常在用System.out.println什么的,读写文件也总是涉及到BufferedReader, 各种Stream,各种Reader, 但是我们确实很少去关注他们之间到底有什么关系,为什么我们要这样写才能进行字节流,进行一些对象的存储等操作妮?我们就来学习下相关的知识,主要是往实践方面去学习,然后最后做个总结,给自己更加清晰的思路..
package com.example;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
/*
*@Description: Java 流(Stream)、文件(File)和IO
*@Author: hl
*@Time: 2018/9/23 11:34
*/
public class FileUtils {
public static void main(String[] args){
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
char c = '0';
String cs = "no";
///< 字符
do {
try {
c = (char)bufferedReader.read();
System.out.println("bufferedReader.read()=" + c);
} catch (IOException e) {
e.printStackTrace();
}
}while (c != 'q');
///< 字符串
do {
try {
cs = (String)bufferedReader.readLine();
System.out.println("bufferedReader.readLine()=" + cs);
} catch (IOException e) {
e.printStackTrace();
}
}while (!cs.equals("end"));
///< Scanner方式字符输入
Scanner scanner = new Scanner(System.in);
String endStr = "no";
while (scanner.hasNext() && !endStr.equals("end")){
System.out.println("scanner.next()=" + (endStr = scanner.next()));
}
///< Scanner方式字符串输入
endStr = "no";
while (scanner.hasNextLine() && !endStr.equals("end")){
System.out.println("scanner.nextLine()=" + (endStr = scanner.nextLine()));
}
scanner.close();
///< 输出就不用说了print println System.out.write
System.out.write('d');
byte[] bytes = new byte[]{'a', 'b', 'c', '\n'};
System.out.write(bytes, 0, bytes.length);
}
}
输入的方式:
1. 创建输入流对象
BufferedReader bufferedReader = newBufferedReader(newInputStreamReader(System.in));
1.1 read()方法提供字符输入 (char)bufferedReader.read();
1.2. readLine()方法提供字符串输入 (String)bufferedReader.readLine();
2. jdk1.5以后的新增封装的方式Scanner Scanner scanner = newScanner(System.in);
2.1 next和nextLine都是读入字符串的方式
String endStr = "no";
endStr = scanner.next();
endStr = scanner.nextLine();
为什么有两种妮 ? (其中重点就是空白是否可以获取到)
next() 与 nextLine() 区别
next():
1、一定要读取到有效字符后才可以结束输入。
2、对输入有效字符之前遇到的空白,next() 方法会自动将其去掉。
3、只有输入有效字符后才将其后面输入的空白作为分隔符或者结束符。
next() 不能得到带有空格的字符串。
nextLine():
1、以Enter为结束符,也就是说 nextLine()方法返回的是输入回车之前的所有字符。
2、可以获得空白。
另外,Scanner还提供了整数、浮点数等基础数据类型的输入(其实本质来讲帮我们实现的数据类型的转换,否则,就需要我们自己进行处理咯 - 小白是这么理解的)
Then,输出我们就经常用了,什么System.out相关的一系列方法,其中System.out.write大家可能用的少,可以了解下。主要是涉及到OutputStream的实现,然后我们来跟一下吧(可以稍微加深我们的印象和加强我们的理解):1234
从System类也能看出,主要就是提供控制台输入输出的操作。另外我们一般跟代码可以发现,最后实现的地方怎么都是这样的代码: throw new Run.....(); 具体实现妮?- 比较好的理解:行的时候,自动转换为rom里面的类来执行(TODO 具体后面我们专门分析..这里留个问题)
既然作为进阶的学习和总结,我们将逐渐深入一些东西才行...否则看源码都费劲...
这篇就先这样吧.....