从文件读取字符串的几种方式
1 使用BufferedReader和FileReader(无法指定读取字符集)
public static void main(String[] args) {StringBuilder content = new StringBuilder();try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) {String line;while ((line = reader.readLine()) != null) {content.append(line).append("\n");}} catch (IOException e) {e.printStackTrace();}System.out.println("文件内容: ");System.out.println(content.toString());}
2 使用BufferedReader、InputStreamReader、FileInputStream(可以指定读取字符集)
public static void main(String[] args) {StringBuilder content = new StringBuilder();try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("file.txt")),"GBK")) {String line;while ((line = reader.readLine()) != null) {content.append(line).append("\n");}} catch (IOException e) {e.printStackTrace();}System.out.println("文件内容: ");System.out.println(content.toString());}
其他不常用的如Files、Scanner我就不举例了
字符串写入文件的几种方式
使用BufferedWriter和FileWriter
public static void main(String[] args) {String content = "这是要写入文件的字符串内容。";try (BufferedWriter writer = new BufferedWriter(new FileWriter("file.txt"))) {writer.write(content);} catch (IOException e) {e.printStackTrace();}}
使用OutputStreamWriter、FileOutputStream(指定字符)
public static void main(String[] args) {String content = "这是要写入文件的字符串内容。";try (OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream("file.txt"),"UTF-8")) {writer.write(content);} catch (IOException e) {e.printStackTrace();}}
使用BufferedWriter、OutputStreamWriter、FileOutputStream(指定字符)
public static void main(String[] args) {String content = "这是要写入文件的字符串内容。";try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("file.txt"),"UTF-8"))) {writer.write(content);} catch (IOException e) {e.printStackTrace();}}
使用PrintWriter
public class WriteToFileExample {public static void main(String[] args) {String content = "这是要写入文件的字符串内容。";try (PrintWriter writer = new PrintWriter("file.txt")) {writer.println(content);} catch (FileNotFoundException e) {e.printStackTrace();}}
}或者在printwriter中:
new PrintWriter(new FileWriter("文件"));
或者指定字符集
new PrintWriter(new OutPutStreamWriter(new FileOutputStream(new File("文件")),"UTF-8"))
区别
OutputStreamWriter:
功能:OutputStreamWriter 是一个字符流通向字节流的桥梁。它将字符按照指定的字符集编码成字节流,并将其写入到 OutputStream 中。
性能:OutputStreamWriter 的主要作用是将字符转换为字节,因此它适用于将字符数据写入到字节流中,比如将字符数据写入文件或网络连接。
使用场景:适用于将字符数据写入到字节流中,并需要指定字符集编码的情况。
BufferedWriter:
功能:BufferedWriter 是用于写入文本的字符输出流,并且它可以提供缓冲区功能,以减少写入操作对底层资源的频繁访问,从而提高性能。
性能:BufferedWriter 的主要作用是提供缓冲区,对于频繁的写入操作,使用 BufferedWriter 可以减少实际的写入磁盘次数,从而提高性能。
使用场景:适用于需要频繁地向文件中写入大量文本数据的情况,可以通过 BufferedWriter 的缓冲功能来提高写入性能。
区别总结:
OutputStreamWriter 主要用于将字符转换为字节并写入到字节流中。
BufferedWriter 主要用于提供缓冲功能,以提高向字符流中写入文本数据的性能。
OutputStreamWriter 是字符流向字节流的桥梁,而 BufferedWriter 是用于字符输出流的缓冲写入。
虽然它们都用于字符输出,但主要的功能和使用场景是不同的,根据具体的需求选择合适的类来实现相应的功能。