JAVA基础(三)—— 输入输出处理
JAVA基础(三)—— 输入输出处理
1 输入解析
//Scanner获取输入
import java.util.Scanner;
Scanner s = new Scanner(System.in);
String input = s.nextLine() ;
s.close();
String [] a = input.split(" ");
//多次换行输入
for (int i=0;i<7;i++) String string1=s.nextLine();
//Scanner类
//获取输入的字符串:Scanner 类的 next() 与 nextLine() 方法
//读取前判断是否还有输入的数据:hasNext 与 hasNextLine
if (scan.hasNext()) String str1 = scan.next();
if (scan.hasNextLine()) String str2 = scan.nextLine();
//int或float类型输入,判断输入的是否是该类型
if (scan.hasNextXXX()) scan.nextXXX();
//输入多个数字,回车隔开,输入非数字结束输入
while (scan.hasNextDouble()) double x = scan.nextDouble();
-
next() 与 nextLine() 区别
- next
- 读到有效字符前的空白全都忽略,读到有效字符后才可以结束输入
- 只有输入有效字符后才将其后面输入的空白作为分隔符或者结束符。
- next不能得到带有空格的字符串
- nextLine
- 以Enter为结束符,也就是说 nextLine()方法返回的是输入回车之前的所有字符。
- 可以获得空白
- next
-
字符串分割
//“.”和“|”和“*”和“\”和“+”都是转义字符,必须得加"\\" String.split("\\."); String.split("\\|"); String.split("\\*"); String.split("\\\"); String.split("\\+") //多个分隔符 使用| String.split("and|or"); //匹配的正则表达式分割 String.split(String regex);
2 读文件写文件
import java.io.*;
//读入TXT文件
//防止文件建立或读取失败,用catch捕捉错误并打印,也可以throw;
//不关闭文件会导致资源的泄露,读写文件都同理
try (FileReader reader = new FileReader(pathname);
// 建立一个对象,它把文件内容转成计算机能读懂的语言
BufferedReader br = new BufferedReader(reader)
) {
String line;
while ((line = br.readLine()) != null) {
// 一次读入一行数据
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
//写入TXT文件
try {
File writeName = new File("output.txt");
writeName.createNewFile(); // 创建新文件,有同名的文件的话直接覆盖
try (FileWriter writer = new FileWriter(writeName);
BufferedWriter out = new BufferedWriter(writer)
) {
out.write("我会写入文件啦1\r\n"); // \r\n即为换行
out.write("我会写入文件啦2\r\n"); // \r\n即为换行
out.flush(); // 把缓存区内容压入文件
}
} catch (IOException e) {
e.printStackTrace();
}