-2
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.println("Does it exist:" + file.exists());
    System.out.println("The file has " + file.length() + "bytes");
    System.out.println("Can it be read? " + file.canRead());
    }
}

I copied this code from my book Introduction to Java Programming, and it compiles correctly but it doesn't create the file, and returns false and zero bytes for the methods. Can someone help please I will give best answer.

8
  • Do you want to create or to read the file? Commented Feb 11, 2017 at 1:05
  • 2
    new java.io.File("image/us.gif"); alone basically does nothing. You need a byte stream of some sort for reading or writing. What are you trying to do? Commented Feb 11, 2017 at 1:06
  • 3
    File is a virtual concept of a File, it doesn't have to exist, instead, if you want to "create" a File, represented by the virtual concept, you should use File#createNewFile - beware, this will create a empty file. Assuming you know of a File on the system, you could point File to it and it will give you better results Commented Feb 11, 2017 at 1:07
  • Right-o. File is basically just a path name. The file it points to may or may not actually exist (that's why there's an .exists() method). It's up to you to create the file if you want to, and put data in it if you desire. The system doesn't do any of that for you. Commented Feb 11, 2017 at 1:14
  • Ok thanks guys I got it now. No answer in comments. Do I just delete or close? Commented Feb 11, 2017 at 1:17

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.