1. Data source
InputStream is essentially byte[], input means that data is obtained from the outside to memory and encapsulated in byte[].
Subclasses:
FileInputStream is to obtain data from files (files, data not in memory);
ByteArrayInputStream obtains data from memory (data that already exists in memory);
eventually, an Object of InputStream type is generated.
2. Code Analysis
2.1 Simply copy files
public static void main(String[] args) throws IOException {
InputStream inputStream = new FileInputStream("D:\\DAY_WORK\\2020\\month_10\\10_月.txt");
OutputStream outputStream = new FileOutputStream("D:\\DAY_WORK\\2020\\month_10\\10_copy.txt");
byte[] bytes = new byte[inputStream.available()];
inputStream.read(bytes);
outputStream.write(bytes);
inputStream.close();
outputStream.close();
}
2.2 Copy files in units of 1024
public static void main(String[] args) throws IOException {
InputStream inputStream = new FileInputStream("D:\\DAY_WORK\\2020\\month_10\\My Favorite 修改说明.docx");
OutputStream outputStream = new FileOutputStream("D:\\DAY_WORK\\2020\\month_10\\My Favorite 修改说明copy.docx");
byte[] bytes = new byte[1024];
int n;
final int end = -1;
while (end != (n = inputStream.read(bytes))) {
outputStream.write(bytes, 0, n);
}
inputStream.close();
outputStream.close();
}
2.3 Add a sentence to the content of the file
public static void main(String[] args) throws IOException {
OutputStream outputStream = new FileOutputStream("D:\\DAY_WORK\\2020\\month_10\\10_copy.txt", true);
String content = "\n今天又是 nice 的一天";
byte[] bytes = content.getBytes();
outputStream.write(bytes);
outputStream.close();
}
3. The difference between outputstream and Writer/FileWriter
The unit of outPutStream is byte; the unit of
Writer/FileWriter is character, which has encoding problems.