字符转换
向文本中写入数据
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
public class NotepadTest {
public static void main(String[] args) throws IOException {
FileOutputStream fos = new FileOutputStream("demofile.txt", true);
Scanner scanner = new Scanner(System.in);
while (true) {
String str = scanner.nextLine();
if ("exit".equalsIgnoreCase(str)) {
break;
}
fos.write(str.getBytes(StandardCharsets.UTF_8));
}
fos.close();
}
}
输出流
public class NotepadTest {
public static void main(String[] args) throws IOException {
FileOutputStream fos = new FileOutputStream("./demofile.txt", true);
OutputStreamWriter opsw = new OutputStreamWriter(fos);
Scanner scanner = new Scanner(System.in);
while (true){
String str = scanner.nextLine();
if ("exit".equalsIgnoreCase(str)) {
break;
}
opsw.write(str);
}
opsw.close();
}
}
使用流连接
public class NotepadTest {
public static void main(String[] args) throws IOException {
FileOutputStream fos = new FileOutputStream("./demofile.txt", true);
OutputStreamWriter opsw = new OutputStreamWriter(fos, StandardCharsets.UTF_8);
BufferedWriter bw = new BufferedWriter(opsw);
PrintWriter pw = new PrintWriter(bw,true);
Scanner scanner = new Scanner(System.in);
while (true){
String str = scanner.nextLine();
if ("exit".equalsIgnoreCase(str)){
break;
}
pw.println(str);
}
pw.close();
}
}