58,455
社区成员
发帖
与我相关
我的任务
分享
读取内容以后存在一个字节数组中,按照保存文件的方式保存到本地。
1.import java.io.File;
2.import java.io.FileInputStream;
3.import java.io.FileOutputStream;
4.import java.io.IOException;
5.import java.text.SimpleDateFormat;
6.import java.util.Date;
7.
8.public class UpdateFile {
9. public static void main(String[] args) throws IOException {
10. // 待复制的文件名
11. String fileName = "WriteFile.txt";
12. // 子目录名
13. String childDir = "backup";
14. new UpdateFile().update(fileName, childDir);
15. }
16.
17. public void update(String fileName, String childDir) throws IOException {
18. File f1, f2, child;
19. // 在fileName和childDir当前目录中分别创建文件对象
20. f1 = new File(fileName);
21. child = new File(childDir);
22. if (f1.exists()) {
23. if (!child.exists())
24. child.mkdir();
25. // 在子目录childDir中创建文件对象
26. f2 = new File(child, fileName);
27. if (!f2.exists() || f2.exists()
28. && (f1.lastModified() > f2.lastModified()))
29. copy(f1, f2);
30. getInfo(f1);
31. getInfo(child);
32. } else
33. System.out.println(f1.getName() + " file not found!");
34. }
35.
36. /**
37. * 复制文件f1至f2
38. *
39. * @param f1
40. * 源文件
41. * @param f2
42. * 目标文件
43. * @throws IOException
44. */
45. public void copy(File f1, File f2) throws IOException {
46. // 创建文件输入输出流对象
47. FileInputStream is = new FileInputStream(f1);
48. FileOutputStream os = new FileOutputStream(f2);
49. // 设定读取的字节数
50. int count, n = 512;
51. byte buffer[] = new byte[n];
52. // 读取输入流
53. count = is.read(buffer, 0, n);
54. while (count != -1) {
55. os.write(buffer, 0, count);
56. count = is.read(buffer, 0, n);
57. }
58. // 关闭输入输出流
59. is.close();
60. os.close();
61. }
62.
63. /**
64. * 取得文件或文件夹信息:路径、修改时间
65. *
66. * @param file
67. * @throws IOException
68. */
69. public static void getInfo(File file) throws IOException {
70. // 初始化时间格式
71. SimpleDateFormat sdf =
72. new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
73. if (file.isFile())
74. // 返回抽象路径名的绝对路径、文件长度、最后修改时间
75. System.out.println("<FILE>\t"
76. + file.getAbsolutePath() + "\t"
77. + sdf.format(new Date(file.lastModified())));
78. else {
79. System.out.println("\t" + file.getAbsolutePath());
80. File[] files = file.listFiles();
81. for (int i = 0; i < files.length; i++)
82. getInfo(files[i]);
83. }
84. }
85.}