[Java] Create File with java.io.File class

    Create a file with some content in some specific location. The reference is here

 /**
    * Write fileContent in a file and save it into FileToCreatePath
    *
    * @param fileContent content of the file
    * @param FileToCreatePath path of the file been saved
    * @throws IOException
    */
   private static void createFile(String fileContent, Path FileToCreatePath) throws IOException
   {
      File file = FileToCreatePath.toFile();
      if (file.createNewFile())
      {
         System.out.println(FileToCreatePath.toString() + " is created!");
      }
      else
      {
         System.out.println(FileToCreatePath.toString() + " already exists.");
      }
      FileWriter writer = new FileWriter(file);
      writer.write(fileContent);
      writer.close();
   }

E.g  if want to create a HelloWorld.txt file, then we just need to use

static final String _txtContent = "Hello World!!!";
static final Path _FilePath = Paths.get(
      System.getenv("APPDATA"),
      "HelloWorld.txt"
   );

// if we want to create different file , like .java, .py or .vbs, we just need to change the name in the _FilePath.

createFile(_txtContent, _FilePath);

猜你喜欢

转载自www.cnblogs.com/Johnsonxiong/p/9880561.html
今日推荐