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/op61 著作权归作者所有。请勿转载和采集!