Java文件操作:读写文件以及文件路径问题

原创 谁践踏了优雅 2024-11-30 20:51 129阅读 0赞

在Java中,处理文件主要涉及到FileInputStream, FileOutputStream, BufferedReader, PrintWriter等类。

  1. 读取文件
    ```java
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;

public class FileReader {
public static void main(String[] args) {
String filePath = “/path/to/your/file.txt”; // 你的文件路径

  1. File file = new File(filePath);
  2. if (file.exists()) { // 检查文件是否存在
  3. FileInputStream fis = null;
  4. try {
  5. fis = new FileInputStream(file); // 打开文件
  6. byte[] buffer = new byte[1024]; // 创建缓冲区
  7. while (fis.read(buffer) != -1) { // 读取文件内容,直到到达末尾或遇到错误
  8. System.out.print(new String(buffer)); // 输出读取到的内容
  9. }
  10. } catch (IOException e) {
  11. e.printStackTrace();
  12. } finally {
  13. if (fis != null) { // 关闭文件流
  14. try {
  15. fis.close();
  16. } catch (IOException e) {
  17. e.printStackTrace();
  18. }
  19. }
  20. }
  21. } else {
  22. System.out.println("File does not exist.");
  23. }
  24. }

}

  1. 2. **写入文件**:
  2. ```java
  3. import java.io.File;
  4. import java.io.FileWriter;
  5. import java.io.IOException;
  6. public class FileWriterExample {
  7. public static void main(String[] args) {
  8. String filePath = "/path/to/your/file.txt"; // 你的文件路径
  9. File file = new File(filePath);
  10. try (FileWriter fw = new FileWriter(file)) { // 打开文件以写入
  11. String content = "Hello, World!"; // 要写入的内容
  12. fw.write(content); // 写入内容到文件
  13. } catch (IOException e) {
  14. e.printStackTrace();
  15. System.out.println("Failed to write to file.");
  16. }
  17. }
  18. }
  1. 文件路径问题
    在Java中,使用File类的构造方法来创建文件对象。File对象需要一个有效的文件路径作为参数。

如果路径是相对的(如相对于当前工作目录),那么Java会根据当前的工作目录来解析这个路径。

例如,如果你有一个相对路径./example.txt,那么它将在你的当前工作目录下查找example.txt文件。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,129人围观)

还没有评论,来说两句吧...

相关阅读