流
在Java中输入流就是从某地方进行数据读取然后输入到我们的Java程序,然后有我们的Java程序再输出到某个地方,这就是一个数据传输的过程。
读取控制台输入的字符:
Java 的控制台输入由 System.in 完成。
为了获得一个绑定到控制台的字符流,你可以把 System.in 包装在一个 BufferedReader 对象中来创建一个字符流。
下面是创建 BufferedReader 的基本语法:
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
- 读取多个字符:
//使用 BufferedReader 在控制台读取字符
import java.io.*;
public class BRRead {
public static void main(String args[]) 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');
}
}
- 读取字符串:
//使用 BufferedReader 在控制台读取字符
import java.io.*;
public class BRReadLines {
public static void main(String args[]) throws IOException {
// 使用 System.in 创建 BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str;
System.out.println("Enter lines of text.");
System.out.println("Enter 'end' to quit.");
do {
str = br.readLine();
System.out.println(str);
} while (!str.equals("end"));
}
}
控制台输出:
在此前已经介绍过,控制台的输出由 print( ) 和 println() 完成。这些方法都由类 PrintStream 定义,System.out 是该类对象的一个引用。
PrintStream 继承了 OutputStream类,并且实现了方法 write()。这样,write() 也可以用来往控制台写操作。
import java.io.*;
//演示 System.out.write().
public class WriteDemo {
public static void main(String args[]) {
int b;
b = 'A';
System.out.write(b);
System.out.write('\n');
}
}
File文件类:
1.成员变量:
import java.io.File;
public class Demo01 {
public static void main(String[] args) {
//File类
//文件:File
//目录(文件夹):directory
//路径:path
//路径分隔符(与系统有关的)<windows里面是 ; linux里面是 : >
System.out.println(File.pathSeparator); // ;
//与系统有关的路径名称分隔符<windows里面是 \ linux里面是/ >
System.out.println(File.separator); // \
}
}
2、构造函数:
import java.io.File;
public class Demo02 {
public static void main(String[] args) {
File file=new File("D:\\java\\b.txt"); //双\\是转义
System.out.println(file);
File file2=new File("D:\\java","a.txt");//父路径、子路径--可以适用于多个文件的!
System.out.println(file2);
File parent=new File("D:\\java");
File file3=new File(parent,"a.txt");//File类的父路径、子路径
System.out.println(file3);
}
}
3、File类的获取及文件的创建和删除、判断:
import java.io.File;
import java.io.IOException;
public class Demo03 {
public static void main(String[] args) throws IOException {
method06();
}
public static void method01(){
File file=new File("D:\\java\\a.txt");
//获取文件对象的绝对路径
System.out.println(file.getAbsolutePath());
File file0=new File("src");//写相对路径的话,会自动转成绝对路径,但是不去检验文件是否真实存在(只会给翻译回来,可能根本不存在) D:\JAVA0322\Day16\src
//获取文件对象的绝对路径
System.out.println(file0.getAbsolutePath());
File file00=new File("aa");//这个根本不存在 D:\JAVA0322\Day16\aa
//获取文件对象的绝对路径
System.out.println(file00.getAbsolutePath());
//获取文件对象的文件名或者目录名
System.out.println(file.getName());
//获取文件对象的路径所对应的字符串 类似于toString()方法
System.out.println(file.getPath());
//获取文件的大小(字节---Long类型)
System.out.println(file.length());
}
//文件创建和删除
public static void method02() throws IOException{
File file=new File("D:\\java\\d");
//创建文件
boolean flag=file.createNewFile();//都是创建的文件(最好都是加上后缀的),不能是文件夹
System.out.println(flag);
}
//文件删除
public static void method03(){
File file=new File("D:\\java\\d");
//删除文件(找不回来了)
boolean flag=file.delete();
System.out.println(flag);
}
//文件判断
public static void method04(){
File file=new File("D:\\java\\a.txt");
//判断该文件对象所对应的文件是否存在
System.out.println(file.exists());
//判断该文件对象是否是文件夹
System.out.println(file.isDirectory());
//判断该文件对象是否是文件
System.out.println(file.isFile());
}
//创建文件夹
public static void method05(){
File file=new File("D:\\java\\d.txt");//windows系统内文件夹名字不区分大小写,最后这个是文件夹的名字
boolean flag=file.mkdir();
System.out.println(flag);
}
//创建文件夹
public static void method06(){
File file=new File("D:\\java\\d\\a\\b");//mkdirs()用于创建多级目录,经常用的方法,不加s不能创建多级目录
boolean flag=file.mkdirs();
System.out.println(flag);
}
}
4、listFiles()方法介绍
import java.io.File;
public class Demo04 {
public static void main(String[] args) {
method03();
}
public static void method01(){
File file=new File("D:\\java");
//获取该路径下的文件和文件夹
String[] arr=file.list();
//遍历
for(String s:arr){
System.out.println(s);//返回文件的全部的名字
}
}
public static void method02(){
File file=new File("D:\\java");
//获取该路径下的文件和文件夹所对应的文件对象
File[] files=file.listFiles();
for(File f:files){
System.out.println(f);//获得的其绝对路径---根本方法
}
}
}
需要注意的是:
①、指定的目录也就是文件夹必须存在;
②、指定的必须是目录。否则会空指针。
4、文件过滤器:
FileFilter 与FilenameFilter都是接口:
public static void method03(){
File file=new File("D:\\java");
//获取该路径下的文件和文件夹所对应(括号内为条件,也就是某个类型)的文件对象
File[] files=file.listFiles(new MyFileFilter());
for(File f:files){
System.out.println(f);//获得的其绝对路径---根本方法
}
}
import java.io.File;
import java.io.FileFilter;
//过滤器:
public class MyFileFilter implements FileFilter{
public boolean accept(File pathname) {
/*//获取文件名
String filename=pathname.getName();
//判断文件名是否以.txt结尾
boolean flag=filename.endsWith(".txt");
return flag;
*/
return pathname.getName().endsWith(".txt");
}
}
递归:
在当前方法内调用自己的现象
//递归
public class Demo01 {
public static void main(String[] args) {
int sum=get(100);
System.out.println(sum);
}
//用递归计算1-100的和
public static int get( int num){
if(num==1){
return 1;
}
return num +get(num-1);
}
}
import java.io.File;
public class Demo02 {
public static void main(String[] args) {
File file=new File("D:\\java");
look(file);
}
public static void look(File file){
//获取该路径下所有的文件夹和文件
File[] files=file.listFiles(new MyFilter());//获得.txt文件和文件夹
//遍历
for(File f:files){
//如果是文件夹则继续寻找
if(f.isDirectory()){
look(f);
}else{//如果不是则打印
System.out.println(f);
}
}
}
}
import java.io.File;
import java.io.FileFilter;
public class MyFilter implements FileFilter {
public boolean accept(File pathname) {
//获取以.txt为后缀的文件
//如果是文件夹,那么放到File[]数组内
if(pathname.isDirectory()){
return true;
}
return pathname.getName().endsWith(".JaVa");
}
}
I/O流:
常用的流:
- 字节流
- 输入流:FileInputStream:
创建方法:
// 方式一:
InputStream f = new FileInputStream("C:/java/hello");
// 方式二:
File f = new File("C:/java/hello");
InputStream out = new FileInputStream(f);
常用方法:
序号 | 方法及描述 |
---|---|
1 | public void close() throws IOException{} 关闭此文件输入流并释放与此流有关的所有系统资源。抛出IOException异常。 |
2 | protected void finalize()throws IOException {} 这个方法清除与该文件的连接。确保在不再引用文件输入流时调用其 close 方法。抛出IOException异常。 |
3 | public int read(int r)throws IOException{} 这个方法从 InputStream 对象读取指定字节的数据。返回为整数值。返回下一字节数据,如果已经到结尾则返回-1。 |
4 | public int read(byte[] r) throws IOException{} 这个方法从输入流读取r.length长度的字节。返回读取的字节数。如果是文件结尾则返回-1。 |
5 | public int available() throws IOException{} 返回下一次对此输入流调用的方法可以不受阻塞地从此输入流读取的字节数。返回一个整数值。 |
-
输出流:FileOutputStream
创建方法:
// 方式一: OutputStream f = new FileOutputStream("C:/java/hello") // 方式二: File f = new File("C:/java/hello"); OutputStream f = new FileOutputStream(f);
常用方法:
序号 | 方法及描述 |
---|---|
1 | public void close() throws IOException{} 关闭此文件输入流并释放与此流有关的所有系统资源。抛出IOException异常。 |
2 | protected void finalize()throws IOException {} 这个方法清除与该文件的连接。确保在不再引用文件输入流时调用其 close 方法。抛出IOException异常。 |
3 | public void write(int w)throws IOException{} 这个方法把指定的字节写到输出流中。 |
4 | public void write(byte[] w) 把指定数组中w.length长度的字节写到OutputStream中。 |
实例:
import java.io.*;
public class fileStreamTest {
public static void main(String args[]) {
try {
byte bWrite[] = { 11, 21, 3, 40, 5 };
OutputStream os = new FileOutputStream("test.txt");
for (int x = 0; x < bWrite.length; x++) {
os.write(bWrite[x]); // writes the bytes
}
os.close();
InputStream is = new FileInputStream("test.txt");
int size = is.available();
for (int i = 0; i < size; i++) {
System.out.print((char) is.read() + " ");
}
is.close();
} catch (IOException e) {
System.out.print("Exception");
}
}
}
//文件名 :fileStreamTest2.java
import java.io.*;
public class fileStreamTest2 {
public static void main(String[] args) throws IOException {
File f = new File("a.txt");
FileOutputStream fop = new FileOutputStream(f);
// 构建FileOutputStream对象,文件不存在会自动新建
OutputStreamWriter writer = new OutputStreamWriter(fop, "UTF-8");
// 构建OutputStreamWriter对象,参数可以指定编码,默认为操作系统默认编码,windows上是gbk
writer.append("中文输入");
// 写入到缓冲区
writer.append("\r\n");
// 换行
writer.append("English");
// 刷新缓存冲,写入到文件,如果下面已经没有写入的内容了,直接close也会写入
writer.close();
// 关闭写入流,同时会把缓冲区内容写入文件,所以上面的注释掉
fop.close();
// 关闭输出流,释放系统资源
FileInputStream fip = new FileInputStream(f);
// 构建FileInputStream对象
InputStreamReader reader = new InputStreamReader(fip, "UTF-8");
// 构建InputStreamReader对象,编码与写入相同
StringBuffer sb = new StringBuffer();
while (reader.ready()) {
sb.append((char) reader.read());
// 转成char加到StringBuffer对象中
}
System.out.println(sb.toString());
reader.close();
// 关闭读取流
fip.close();
// 关闭输入流,释放系统资源
}
}
2**.字符流**
- 输入流:InputStremReader
创建:
FileInputStream fileInputStream = new FileInputStream(file);
//获取字符输入流
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream,"UTF-8");
实例:
File file = new File("F:/a.txt");
if (!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}else {
System.out.println("文件已存在");
try{
FileInputStream fileInputStream = new FileInputStream(file);
//获取字符输入流
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream,"gbk");
char[] c = new char[64];
int read = inputStreamReader.read(c);
System.out.println( new String(c));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
- 输入流:BufferedReader
// 使用InputStreamReader
FileInputStream fileInputStream = new FileInputStream(file);
//获取字符输入流
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line = null;
while ((line=bufferedReader.readLine())!= null){
System.out.println(line);
}
- 输出流:BufferedWriter
import java.io.*;
public class ReaderDeno {
public static void main(String[] args) {
File file = new File("F:/a.txt");
File file1 = new File("F:/b.txt");
if (!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}else {
System.out.println("文件已存在");
try{
// 使用InputStreamReader
FileInputStream fileInputStream = new FileInputStream(file);
//获取字符输入流
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
FileOutputStream fileOutputStream = new FileOutputStream(file1);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
String line = null;
while ((line=bufferedReader.readLine())!= null){
System.out.println(line);
bufferedWriter.write(line);
bufferedWriter.newLine(); // 换行
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
bufferedwriter.close();
}
}
}
}
- 对象流:ObjectOutputStream和ObjectInputSteam
public class Dog implements Serializable { // 支持序列化
private static final long serialVersionUID = -7719018362866837078L;
private String name;
private int age;
public Dog() {}
public Dog(String name, int age) {
this.name = name;
this.age = age;
}
//省略Getter/Setter方法
...
@Override
public String toString() {
return "Dog{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
public class ObjectStreamDemo {
public static void main(String[] args) {
Dog dog = new Dog("金毛", 2);
File file = new File("F:\\demo\\dog.obj"); //.obj扩展名是随意写的,可随意更换
try {
OutputStream os = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(dog);
oos.flush();
oos.close();
os.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class ObjectStreamDemo {
public static void main(String[] args) {
File file = new File("F:\\demo\\dog.obj");
try {
InputStream is = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(is);
Dog dog = (Dog) ois.readObject();
System.out.println(dog);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Scanner类:
语法:
Scanner s = new Scanner(System.in);
- 使用 next 方法:
ScannerDemo.java 文件代码:
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// 从键盘接收数据
// next方式接收字符串
System.out.println("next方式接收:");
// 判断是否还有输入
if (scan.hasNext()) {
String str1 = scan.next();
System.out.println("输入的数据为:" + str1);
}
scan.close();
}
}
执行以上程序输出结果为:
next方式接收:
runoob com
输入的数据为:runoob
- 使用 nextLine 方法:
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// 从键盘接收数据
// nextLine方式接收字符串
System.out.println("nextLine方式接收:");
// 判断是否还有输入
if (scan.hasNextLine()) {
String str2 = scan.nextLine();
System.out.println("输入的数据为:" + str2);
}
scan.close();
}
}
执行以上程序输出结果为:
nextLine方式接收:
runoob com
输入的数据为:runoob com
next() 与 nextLine() 区别
next():
- 1、一定要读取到有效字符后才可以结束输入。
- 2、对输入有效字符之前遇到的空白,next() 方法会自动将其去掉。
- 3、只有输入有效字符后才将其后面输入的空白作为分隔符或者结束符。
- next() 不能得到带有空格的字符串。
nextLine():
-
1、以Enter为结束符,也就是说 nextLine()方法返回的是输入回车之前的所有字符。
-
2、可以获得空白。
-
对不同数据类型的支持:
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// 从键盘接收数据
int i = 0;
float f = 0.0f;
System.out.print("输入整数:");
if (scan.hasNextInt()) {
// 判断输入的是否是整数
i = scan.nextInt();
// 接收整数
System.out.println("整数数据:" + i);
} else {
// 输入错误的信息
System.out.println("输入的不是整数!");
}
System.out.print("输入小数:");
if (scan.hasNextFloat()) {
// 判断输入的是否是小数
f = scan.nextFloat();
// 接收小数
System.out.println("小数数据:" + f);
} else {
// 输入错误的信息
System.out.println("输入的不是小数!");
}
scan.close();
}
}
*声明:此博文为个人学习笔记,参考了菜鸟教程等网络资源,如有侵权,请私信告知!*