作业:将work.txt中的内容复制到workcopy.txt中
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
package
com.java.homework;
import
java.io.FileInputStream;
import
java.io.FileNotFoundException;
import
java.io.FileOutputStream;
import
java.io.IOException;
/**
* 将work.txt中的内容复制到workcopy.txt中
* @author Administrator
* time 2019.3.7
*/
public
class
Copy {
public
static
void
main(String[] args) {
FileInputStream fis =
null
;
FileOutputStream fos =
null
;
try
{
fis =
new
FileInputStream(
"work.txt"
);
fos =
new
FileOutputStream(
"workcopy.txt"
);
int
r = -
1
;
String s =
""
;
//判断是否读取到末尾
while
((r = fis.read())!=-
1
) {
//将读取出来的数据再转成char类型
s += (
char
)r;
}
//在控制台上输出work.txt中的内容
System.out.println(s);
//将从work.txt读取出来的数据放在byte[] b数组中
byte
[] b = s.getBytes();
//将存在byte[] b数组中的数组输出到workcopy.txt
fos.write(b,
0
, b.length);
}
catch
(FileNotFoundException e) {
e.printStackTrace();
}
catch
(IOException e) {
e.printStackTrace();
}
finally
{
try
{
if
(fos!=
null
) {
fos.close();
}
if
(fis!=
null
) {
fis.close();
}
}
catch
(IOException e) {
e.printStackTrace();
}
}
}
}
|
结果示例:
work.txt中的内容
控制台上的内容:
复制后workcopy中的内容是: