第三题 请用键盘循环随机输入三段字符串1:将三段字符串用Stringbuffer类拼接成一个字符串并将该字符串写入cinputDemotxt文件;写文件用字节流实现2:读取cinputDemotxt文件并打印文件内容读文件用字节流实现3:将cinputDemotxt文件中的内容复制到cinputDemo2txt文件中读写文件用字节流实现使用java
以下是Java代码实现:
import java.io.*;
public class InputDemo { public static void main(String[] args) { // 第一步:循环随机输入三段字符串 String[] inputs = new String[3]; for (int i = 0; i < 3; i++) { System.out.println("请输入第" + (i+1) + "段字符串:"); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); try { inputs[i] = reader.readLine(); } catch (IOException e) { e.printStackTrace(); } }
// 第二步:将三段字符串拼接成一个字符串,并写入文件
StringBuffer sb = new StringBuffer();
for (String input : inputs) {
sb.append(input);
}
String content = sb.toString();
try {
FileOutputStream fos = new FileOutputStream("c:\\inputDemo.txt");
fos.write(content.getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
// 第三步:读取文件内容并打印
try {
FileInputStream fis = new FileInputStream("c:\\inputDemo.txt");
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fis.read(buffer)) != -1) {
System.out.print(new String(buffer, 0, len));
}
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
// 第四步:将文件内容复制到另一个文件
try {
FileInputStream fis = new FileInputStream("c:\\inputDemo.txt");
FileOutputStream fos = new FileOutputStream("c:\\inputDemo2.txt");
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
fis.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
原文地址: https://www.cveoy.top/t/topic/fNdL 著作权归作者所有。请勿转载和采集!