【问题标题】:How do I write to a File stored in a path in Java如何写入存储在 Java 路径中的文件
【发布时间】:2021-01-24 14:49:09
【问题描述】:

我有一个这样的路径变量:

Path output; 

这个路径在main-method中初始化。

我想检查此路径中是否存在文件 如果是这样的话 - 将一个字符串写入该文件。 否则使用给定路径创建一个新文件并写入 字符串。

//void parseOutput(String s){
//if (file in path exists)
//   write(s in file from path)
  else
     File f = new File(String.valueOf(output)); 
     write String in f

【问题讨论】:

    标签: java file path


    【解决方案1】:
    You can try this :
    
    import java.io.*;
    class FileDemo {
        public static void main(String str[]) {
            String path = "E:/myfile.txt";
            File file = new File(path);
            if(file.exists()) {
                System.out.println("File is exist..!!!");
            } else {
                try {
                    FileWriter fileWriter = new FileWriter(path);
                    fileWriter.write("This is my first file..!!");
                    fileWriter.close();
                    System.out.println("File has some content..!!");
                } catch(Exception exception) {
                    System.out.println(exception.getMessage());
                }
            }
            
        }
    }
    

    【讨论】:

      【解决方案2】:

      如果你有一个路径,那么将它转换为字符串并使用文件构造函数真的没有意义。

      要检查文件是否存在,您可以使用Files exists

      要添加到现有文件,请查看带有APPEND OpenOption 集的Files.newBufferedWriter

      完整示例:

      Path path = Paths.get("/path/to/file.txt");
      
      try (BufferedWriter bufferedWriter = Files.newBufferedWriter(
              path, StandardOpenOption.APPEND, StandardOpenOption.CREATE);
           PrintWriter printWriter = new PrintWriter(bufferedWriter))
      {
          printWriter.println("This is a line");
      }
      

      【讨论】:

        【解决方案3】:

        您可能想在 File 类中使用 exists() 方法。这是您可以使用的示例:

        public void writeOnFile(String path, String str) throws FileNotFoundException {
                PrintWriter out;
                File file = new File(path);
        
                if (file.exists()){
                    out = new PrintWriter(file.getPath());
                    out.println(str);
                }
        }
        

        【讨论】:

          猜你喜欢
          • 2014-07-29
          • 2020-11-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-11-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多