Java 字节流操作文件:读取、写入和复制示例
import java.io.*;
public class InputDemo {
public static void main(String[] args) throws IOException {
String str1, str2, str3;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println('请输入第一个字符串:');
str1 = br.readLine();
System.out.println('请输入第二个字符串:');
str2 = br.readLine();
System.out.println('请输入第三个字符串:');
str3 = br.readLine();
// 拼接字符串
StringBuffer sb = new StringBuffer();
sb.append(str1).append(str2).append(str3);
String content = sb.toString();
// 写入文件
FileOutputStream fos = new FileOutputStream('c:\inputDemo.txt');
fos.write(content.getBytes());
// 读取文件
FileInputStream fis = new FileInputStream('c:\inputDemo.txt');
int len = 0;
byte[] buffer = new byte[1024];
while ((len = fis.read(buffer)) != -1) {
System.out.print(new String(buffer, 0, len));
}
// 复制文件
FileInputStream fis2 = new FileInputStream('c:\inputDemo.txt');
FileOutputStream fos2 = new FileOutputStream('c:\inputDemo2.txt');
len = 0;
while ((len = fis2.read(buffer)) != -1) {
fos2.write(buffer, 0, len);
}
fos.close();
fis.close();
fis2.close();
fos2.close();
}
}
原文地址: https://www.cveoy.top/t/topic/op6V 著作权归作者所有。请勿转载和采集!