-1

So I was making a program called "TextCreator", and I ran into a problem, and it was that my program was not creating files. I wanted to make a file called "file.txt", and here's my code:

 String fileName = TxtName.getText();
  File file = new File("file.txt");

Because this was not working, I tried creating a file on my pc called "file.txt", and that did not work either. I am using java.io.file.

  • 5
    Does this answer your question? [How do I create a file and write to it?](https://stackoverflow.com/questions/2885173/how-do-i-create-a-file-and-write-to-it) – Tobias Mar 10 '21 at 13:35
  • thank you! I guess I did not notice the "creating a text file" part of the question. – user15132300 Mar 10 '21 at 13:39
  • You may want to take a look at `java.nio` if you want to create a file nowadays. – deHaar Mar 10 '21 at 14:13

1 Answers1

0

I guess you're missing to actually 'create' the file. Without any file operation nothing will actually happen in your file system, you simply created a java object describing a file by name.

E.g. to create an empty file you can call

file.createNewFile();

https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/File.html#createNewFile()

Or you can check the file exists (before trying to create a new one)

if(!file.exists) {
    file.createNewFile();
}

As mentioned by deHaar I'd recommend looking into java.nio.file.Files which offers a more modern API.

cor3000
  • 936
  • 1
  • 6
  • 16