在程序中定义一字符串”hello,how are you!”,分别用字节流和字符流实现将该字符串保存到d:\t2_1.txt, d:\t2_2.txt中,程序分别保存为Test2_1.java和Test2_2.java。
时间: 2024-03-07 14:47:54 浏览: 95
好的,这是一份使用Java语言实现的代码示例,可以实现您的需求:
```java
import java.io.*;
public class Test2_1 {
public static void main(String[] args) {
String str = "hello,how are you!";
// 使用字节流保存字符串到d:\t2_1.txt
try (FileOutputStream fos = new FileOutputStream("d:\\t2_1.txt")) {
byte[] bytes = str.getBytes();
fos.write(bytes);
System.out.println("保存到d:\\t2_1.txt成功!");
} catch (IOException e) {
System.out.println("保存到d:\\t2_1.txt失败!" + e.getMessage());
}
// 使用字符流保存字符串到d:\t2_2.txt
try (FileWriter fw = new FileWriter("d:\\t2_2.txt")) {
fw.write(str);
System.out.println("保存到d:\\t2_2.txt成功!");
} catch (IOException e) {
System.out.println("保存到d:\\t2_2.txt失败!" + e.getMessage());
}
}
}
```
```java
import java.io.*;
public class Test2_2 {
public static void main(String[] args) {
// 从d:\t2_1.txt读取字节流并保存为字符串
try (FileInputStream fis = new FileInputStream("d:\\t2_1.txt")) {
byte[] bytes = new byte[fis.available()];
fis.read(bytes);
String str = new String(bytes);
System.out.println("从d:\\t2_1.txt读取的字符串为:" + str);
} catch (IOException e) {
System.out.println("从d:\\t2_1.txt读取字符串失败!" + e.getMessage());
}
// 从d:\t2_2.txt读取字符流并保存为字符串
try (FileReader fr = new FileReader("d:\\t2_2.txt")) {
char[] chars = new char[1024];
StringBuilder sb = new StringBuilder();
int len;
while ((len = fr.read(chars)) != -1) {
sb.append(chars, 0, len);
}
String str = sb.toString();
System.out.println("从d:\\t2_2.txt读取的字符串为:" + str);
} catch (IOException e) {
System.out.println("从d:\\t2_2.txt读取字符串失败!" + e.getMessage());
}
}
}
```
阅读全文