1.2.1 如何写出文本输出
可使用 PrintWriter/PrintStream 的 println 方法,
构造器两个参数分别代表:输出流,是否自动刷新缓存(不自动关闭前需要flush才能读取完整内容)
❤🧡💛💚💙💜🤎🖤❤🧡💛💚💙💜🤎🖤❤🧡💛💚💙💜🤎🖤
import java.io.*;
import java.nio.charset.StandardCharsets;
public class Main {
public static void main(String[] args){
PrintWriter pw = null;
PrintStream ps = null;
try {
String str = "Returns <tt>true</tt> if this map maps one or more keys to the\n" +
"specified value. More formally, returns <tt>true</tt> if and only if\n" +
"this map contains at least one mapping to a value <tt>v</tt> such that\n" +
"<tt>(value==null ? v==null : value.equals(v))</tt>. This operation\n" +
"will probably require time linear in the map size for most\n" +
"implementations of the <tt>Map</tt> interface.";
pw = new PrintWriter(new FileWriter("a.properties"),true);
String[] items = str.split("\n");
pw.println("PrintWriter 写入:");
for(String line: items){
pw.println(line);
}
ps = new PrintStream(new FileOutputStream("a.properties"),true);
ps.println("PrintStream 写入:");
for(String line: items){
ps.println(line);
}
}catch (IOException e){
e.printStackTrace();
}finally {
if(pw!=null){
pw.close();
}
if(ps!=null){
ps.close();
}
}
}
}
❤🧡💛💚💙💜🤎🖤❤🧡💛💚💙💜🤎🖤❤🧡💛💚💙💜🤎🖤
结果文件(后覆盖前):
用法和 System.out 基本相同
🚗🚓🚕🛺🚙🚌🚐🚎🚑🚒🚚🚛🚜🚘🚔🚖🚍🦽🦼🛹🚲🛴🛵🏍
🚗🚓🚕🛺🚙🚌🚐🚎🚑🚒🚚🚛🚜🚘🚔🚖🚍🦽🦼🛹🚲🛴🛵🏍
1.2.2 如何读入文本输入
可用 PrintWriter/PrintStream, 常用的输入类 Scanner 使用的 System.in 就是 PrintStream
另 PrintWriter 读入可以用BufferedReader包装一下,里面有个很好用的方法 readLine
Scanner 可读取内容【虽说可以读取基本类型,一旦包括换行符就会产生奇怪的问题】, 常用方法:
hasNextLine() 还有没有没读取的内容
nextLine() 读取一行内容(注意如果最后未使用hasNextLine()判断,导致读取失败会抛异常)
具体事例如下:
❤🧡💛💚💙💜🤎🖤❤🧡💛💚💙💜🤎🖤❤🧡💛💚💙💜🤎🖤
public class Main {
public static void main(String[] args){
BufferedReader br = null;
Scanner sc = null;
try {
System.out.println("BufferedReader读取:");
br = new BufferedReader(new FileReader("a.properties"));
String line = null;
while ((line=br.readLine())!=null){
System.out.println(line);
}
System.out.println();
System.out.println("Scanner读取:");
//Scanner
sc = new Scanner(new FileReader("a.properties"));
while (sc.hasNextLine()){
System.out.println(sc.nextLine());
}
}catch (IOException e){
e.printStackTrace();
}finally {
if(br!=null){
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(sc!=null){
sc.close();
}
}
}
}
❤🧡💛💚💙💜🤎🖤❤🧡💛💚💙💜🤎🖤❤🧡💛💚💙💜🤎🖤
控制台结果:
🚗🚓🚕🛺🚙🚌🚐🚎🚑🚒🚚🚛🚜🚘🚔🚖🚍🦽🦼🛹🚲🛴🛵🏍
🚗🚓🚕🛺🚙🚌🚐🚎🚑🚒🚚🚛🚜🚘🚔🚖🚍🦽🦼🛹🚲🛴🛵🏍
相关内容:选择 《Java核心技术 卷1》查找相关笔记
评论🌹点赞👍收藏✨关注👀,是送给作者最好的礼物,愿我们共同学习,一起进步
公众号 钰娘娘知识汇总