Java not creating file

后端 未结 1 890
没有蜡笔的小新
没有蜡笔的小新 2021-01-29 12:50
package com.company;

public class Main {

    public static void main(String[] args) {
    java.io.File file = new java.io.File(\"image/us.gif\");
    System.out.printl         


        
1条回答
  •  醉梦人生
    2021-01-29 13:26

    You will have to create the file manually unless it already exists. Creating a new File object should not be confused with creating a file in the filesystem.

    To create the file you will have to use the method createFile(); which exists in the class File:

    File someFile = new File("path.to.file");
    someFile.createFile();
    

    It would also be a good idea to check if the file exists before creating it to avoid overwriting it. this can be done by:

    File someFile = new File("path.to.file");
    if(!someFile.exists()) {
        someFile.createFile();
    }
    

    This will create a new empty file. That means that it's length will be 0. To write to the file you will need a byte stream. For example, using a FileWriter:

    File test = new File("SomeFileName.txt");
    FileWriter fw = new FileWriter(test);
    fw.append("Hello! :D");
    fw.close();
    


    Note: Some methods i used in the examples above throw exceptions which you will have to handle.

    0 讨论(0)
提交回复
热议问题