IO流第39天(PrintStream,PrintWriter,Properties)
打印流
只有输出流,没有输入流
PrintStream字节打印流

public static void main(String[] args) throws FileNotFoundException {
PrintStream out = System.out;
//在默认情况下,PrintStream输出位置是标准输出,即显示器
out.println("hello,world");
out.close();
System.out.println();
//修改打印流输出的位置
//1,输出位置修改成d:\\qwe.txt
//2,将 hello,龚嘉乐,加油 输出到 d:\qwe.txt
System.setOut(new PrintStream("d:\\qwe.txt"));
System.out.println("hello,龚嘉乐,加油");
}
PrintWrite字符打印流

//直接打印到控制台
PrintWriter printWriter = new PrintWriter(System.out);
//打印到指定位置
PrintWriter printWriter = new PrintWriter(new FileWriter("d:\\a1.txt"));
printWriter.println("好的收到");
printWriter.close();
Properties
- 专门用于读取配置文件的集合类
配置文件格式:
键=值
键=值 - 注意:键值对不需要有空格,只不需要用引号引起来,默认类型是String
- Properties常用方法
- load:加载配置文件的键值对到Properties对象
- list:将数据显示到指定设备/流对象
- getProperty(key):根据键获取值
- getProperty(key,value):设置键值对到Properties对象中
- store:将Properties中的键值对存储到配置文件,在idea中,保存信息到配置文件,如果含有中文,会存储unicode码
案例:使用Properties完成对mysql.properties
public static void main(String[] args) throws IOException {
//使用Properties类来读取mysql.properties文件
//1,创建properties对象
Properties properties = new Properties();
//2,加载指定文件
properties.load(new FileReader("src\\mysql.properties"));
//3,把键值对显示在控制台
properties.list(System.out);
//4根据键获取对应的值
System.out.println(properties.getProperty("ip"));
}

案例2:使用Properties添加键值对到mysql2.properties中
//使用Properties 来创建和修改配置文件
Properties properties = new Properties();
//创建文件
properties.setProperty("charset","utf-8");
properties.setProperty("user","汤姆");//保存的是中文的unicode
properties.setProperty("pwd","123456");
//将键值对存储到文件中
properties.store(new FileOutputStream("src\\mysql2.properties"),null);
System.out.println("配置文件保存成功");


浙公网安备 33010602011771号