package com.hncu.convertedio;
import java.io.*;
import java.nio.charset.Charset;
public class ConvertedDemo1 {
public static void main(String[] args) throws IOException {
//method1();
//method2();
//在JDK11之后,字符流新推出了一个构造,也可以指定编码表
FileReader fr = new FileReader("C:\\Users\\apple\\Desktop\\a.txt", Charset.forName("gbk"));
int ch;
while ((ch = fr.read())!=-1){
System.out.println((char) ch);
}
fr.close();
}
private static void method2() throws IOException {
//如何解决乱码现象
//文件是什么码表,那么咱们就必须使用什么码表去读取.
//我们就要指定使用GBK码表去读取文件.
InputStreamReader isr = new InputStreamReader(new FileInputStream("C:\\Users\\apple\\Desktop\\a.txt"),"gbk");
int ch;
while((ch = isr.read())!=-1){
System.out.println((char) ch);
}
isr.close();
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("C:\\Users\\apple\\Desktop\\b.txt"),"UTF-8");
osw.write("我爱学习,谁也别打扰我");
osw.close();
}
//这个方法直接读取会产生乱码
//因为文件是GBK码表
//而idea默认的是UTF-8编码格式.
//所以两者不一致,导致乱码
private static void method1() throws IOException {
FileReader fr = new FileReader("C:\\Users\\apple\\Desktop\\a.txt");
int ch;
while ((ch = fr.read())!=-1){
System.out.println((char) ch);
}
fr.close();
}
}
package com.hncu.propertiesio;
import java.util.Properties;
import java.util.Set;
public class PropertiesDemo2 {
public static void main(String[] args) {
//Object setProperty(String key, String value) --- put
//设置集合的键和值,都是String类型,底层调用 Hashtable方法 put
Properties prop = new Properties();
prop.setProperty("江苏","南京");
prop.setProperty("安徽","南京");
prop.setProperty("山东","济南");
System.out.println(prop);
//String getProperty(String key) --- get
//使用此属性列表中指定的键搜索属性
/* String value = prop.getProperty("江苏");
System.out.println(value);*/
//Set<String> stringPropertyNames() --- keySet
//从该属性列表中返回一个不可修改的键集,其中键及其对应的值是字符串
Set<String> keys = prop.stringPropertyNames();
for (String key : keys) {
String value = prop.getProperty(key);
System.out.println(key + "=" + value);
}
}
}
package com.hncu.propertiesio;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
public class PropertiesDemo3 {
public static void main(String[] args) throws IOException {
//void load(Reader reader) 将本地文件中的键值对数据读取到集合中
//void store(Writer writer, String comments) 将集合中的数据以键值对形式保存在本地
//读取
Properties prop = new Properties();
FileReader fr = new FileReader("prop.properties");
//调用完了load方法之后,文件中的键值对数据已经在集合中了.
prop.load(fr);
fr.close();
System.out.println(prop);
}
}
package com.hncu.propertiesio;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;
public class PropertiesDemo4 {
public static void main(String[] args) throws IOException {
//void load(Reader reader) 将本地文件中的键值对数据读取到集合中
//void store(Writer writer, String comments) 将集合中的数据以键值对形式保存在本地
Properties prop = new Properties();
prop.put("zhangsan","123");
prop.put("lisi","456");
prop.put("wangwu","789");
FileWriter fw = new FileWriter("prop.properties");
prop.store(fw,null);
fw.close();
}
}