Java-IO流采用转换流指定编码方式及Properties类的使用
采用InputStreamReader、OutputStreamWriter进行编码限定
如果在创建的时候,不指定编码 即 InputStreamReader reader = new InputStreamReader(Files.newInputStream(path), “GBK”) 不指定 GBK 编码,则默认采用 UTF-8编码
package com.boot.test;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
/**
* @author bbyh
* @date 2022/11/3 0003 0:17
* @description
*/
public class Test {
public static void main(String[] args) {
String filePath = "D:/test.txt";
Path path = Paths.get(filePath);
char[] buf = read(path);
write(path, buf);
}
public static void write(Path path, char[] buf) {
try (OutputStreamWriter writer = new OutputStreamWriter(Files.newOutputStream(path), "GBK")) {
writer.write(buf);
writer.close();
System.out.println("Write Success");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static char[] read(Path path) {
char[] buf = new char[10];
try (InputStreamReader reader = new InputStreamReader(Files.newInputStream(path), "GBK")) {
int read = reader.read(buf);
System.out.println(read);
System.out.println(new String(buf));
System.out.println("Success");
} catch (IOException e) {
throw new RuntimeException(e);
}
return buf;
}
}
采用处理流BufferedReader、BufferedWriter进行修饰一下更方便操作
package com.boot.test;
import java.io.*;
import java.nio.file.*;
/**
* @author bbyh
* @date 2022/11/3 0003 0:17
* @description
*/
public class Test {
public static void main(String[] args) {
String filePath = "D:/test.txt";
Path path = Paths.get(filePath);
String str = read(path);
write(path, str);
}
public static void write(Path path, String str) {
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(Files.newOutputStream(path), "GBK"))) {
writer.write(str);
writer.close();
System.out.println("Write Success");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static String read(Path path) {
String readLine;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(Files.newInputStream(path), "GBK"))) {
readLine = reader.readLine();
System.out.println(readLine);
System.out.println("Success");
} catch (IOException e) {
throw new RuntimeException(e);
}
return readLine;
}
}
Properties类的使用
用于处理配置文件的
mysql.properties的内容
user=test
pwd=1234
ip=192.168.0.1
package com.boot.test;
import java.io.*;
import java.util.Properties;
/**
* @author bbyh
* @date 2022/11/3 0003 0:17
* @description
*/
public class Test {
public static void main(String[] args) throws IOException {
String filePath = "src/mysql.properties";
Properties properties = new Properties();
properties.load(new FileReader(filePath));
properties.list(System.out);
System.out.println(properties.getProperty("user"));
properties.setProperty("unicode", "GBK");
properties.setProperty("user", "GBK");
properties.store(new FileWriter(filePath), "Test add");
}
}