BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("D:\\java学习代码\\iotest\\io.txt"),"GBK"));
时间: 2023-09-28 09:10:47 浏览: 57
This line of code creates a BufferedWriter object which writes to a file named "io.txt" located in the directory "D:\java学习代码\iotest\". The data written to the file will be encoded using the character set "GBK". The code uses a FileOutputStream to write bytes to the file, and an OutputStreamWriter to convert the bytes to characters using the specified character set. Finally, a BufferedWriter is used to buffer the output and improve performance.
相关问题
将这段代码改为续写文件 FileOutputStream fileOutputStream = new FileOutputStream("factoryer.txt"); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8"); BufferedWriter writer = new BufferedWriter(outputStreamWriter);
要将这段代码修改为续写文件,可以在FileOutputStream的构造函数中传入第二个参数true,表示以追加的方式打开文件。另外,可以在BufferedWriter的构造函数中传入FileOutputStream对象,以实现续写文件的功能。以下是修改后的示例代码:
```java
import java.io.*;
public class FileWriterAppendExample {
public static void main(String[] args) {
String fileName = "factoryer.txt";
String content = "Hello, world!";
try {
FileOutputStream fileOutputStream = new FileOutputStream(fileName, true); // 第二个参数为true表示续写文件
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
BufferedWriter writer = new BufferedWriter(outputStreamWriter);
writer.write(content);
writer.newLine(); // 换行
writer.close();
System.out.println("内容已经成功续写到文件" + fileName + "中。");
} catch (IOException e) {
System.out.println("写入文件出错:" + e.getMessage());
}
}
}
```
在上面的代码中,我们在FileOutputStream的构造函数中传入了第二个参数true,以实现续写文件的功能。另外,我们还在BufferedWriter的构造函数中传入了FileOutputStream对象,以实现续写文件的功能。注意,如果文件不存在,FileOutputStream会自动创建一个新文件。另外,我们还使用了newLine()方法来换行,以使文件内容更加清晰。
package java_text; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class text3 { public static void main(String[] args) { try { BufferedReader fis = new BufferedReader(new FileReader("D:\\Java\\JavaSpace\\java_text\\src\\java_text\\Source.txt")); BufferedWriter ois = new BufferedWriter(new FileWriter("D:\\Java\\JavaSpace\\java_text\\src\\java_text\\dost.txt")); String line; int num = 0; while ((line = fis.readLine()) != null) { num++; ois.write(num + ": " + line+"\n"); } fis.close(); ois.close(); } catch (IOException e) { e.printStackTrace(); } } }为什么在dost文件里是乱码
这是因为在写入文件时,没有指定写入文件的编码格式。在这个例子中,文件的编码格式使用的是系统默认值,这可能会导致乱码。为了解决这个问题,你可以在创建 BufferedWriter 对象时,指定写入文件的编码格式,例如:
```
BufferedWriter ois = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("D:\\Java\\JavaSpace\\java_text\\src\\java_text\\dost.txt"), "UTF-8"));
```
这样写入文件的编码格式就是 UTF-8,而不会出现乱码。
阅读全文