自建商城系统还是 SaaS 平台?2026年越来越多企业开始重新选择——企业做电商,真正重要的不是上线快,而是未来还能不能持续发展
2026/6/8 18:02:21
File不读写内容,只负责路径表示和文件/目录管理。
File file = new File("data.txt"); File dir = new File("C:/test"); // 最常用的方法 file.exists(); // 是否存在 file.isFile(); // 是否为文件 file.isDirectory(); // 是否为目录 file.getName(); // 文件名 file.getAbsolutePath(); // 绝对路径 file.length(); // 文件大小(字节) file.createNewFile(); // 创建文件 file.mkdirs(); // 递归创建目录 file.delete(); // 删除 file.listFiles(); // 列出目录内容File dir = new File("."); File[] files = dir.listFiles(); for (File f : files) { System.out.println((f.isDirectory() ? "[DIR] " : "[FILE] ") + f.getName()); }int read() // 读一个字节,返回 0~255,结尾返回 -1 int read(byte[] b) // 读一批字节到数组,返回实际读取长度 void close()try (FileInputStream fis = new FileInputStream("data.txt")) { byte[] buf = new byte[1024]; int len; while ((len = fis.read(buf)) != -1) { System.out.write(buf, 0, len); // 不要用 println,会乱码 } }void write(int b) // 写一个字节(低8位) void write(byte[] b) // 写整个数组 void write(byte[] b, int off, int len) // 写数组的指定部分// 覆盖写入(默认) try (FileOutputStream fos = new FileOutputStream("out.txt")) { fos.write("Hello".getBytes()); } // 追加写入(第二个参数传 true) try (FileOutputStream fos = new FileOutputStream("out.txt", true)) { fos.write("World".getBytes()); }直接读写大文件很慢,加 Buffered 包装可提升 10x 以上性能
把前面所有知识点串起来,这是最实用的代码:
public static void copy(String src, String dst) throws IOException { try (InputStream in = new BufferedInputStream(new FileInputStream(src)); OutputStream out = new BufferedOutputStream(new FileOutputStream(dst))) { byte[] buf = new byte[8192]; int len; while ((len = in.read(buf)) != -1) { out.write(buf, 0, len); } } }把
new XXX()写在try()括号里,Java 自动帮你关流,不用手写finally。
// ✅ 推荐:自动关流 try (FileInputStream fis = new FileInputStream("a.txt")) { // 使用 fis } // ❌ 不推荐:手动关流,代码冗长且容易漏 FileInputStream fis = null; try { fis = new FileInputStream("a.txt"); } finally { if (fis != null) fis.close(); }| 要点 | 说明 |
|---|---|
File不读写 | 只管路径、属性、目录操作 |
用try-with-resources | 自动关流,标准写法 |
用Buffered包装 | 大文件必备,性能提升显著 |
| 追加模式 | new FileOutputStream(path, true) |
| 文本编码 | 用getBytes("UTF-8")明确指定 |
如有疑问欢迎留言交流