top of page
Search

How to create a .txt file with Java.

Create a text file. Nothing easier, right? Right-click, new, text document, and you're done... But how do you do that from within the code? That's what I'm going to show you how to do today.


Especially for those starting in programming, it's not common to work with text file manipulation or any other type of file. Values are stored within variables or at most in a database, and that's more than enough. In fact, these are the most usual and simplest ways to store data. However, in some situations, creating text files may be necessary. For example, if I want to provide a report that I extracted from my database as a PDF to someone, how do I do that within the system?


You will see next that it's not rocket science. What you have to do is:


Step 1: Create your Java project structure.


Depending on the IDE you use, this step may be slightly different, but the core of the issue is: create the Java project, create the package, and the class where you will write your code. If you have any doubts about how to do this, by clicking here you have access to an exclusive post on that.



Step 2: Import Classes.

Java itself already provides classes that allow the creation of files of any type. These useful classes are the File class and the IOException class. In the File class, the methods for creating the file itself are described, and the IOException class is used to perform (in this case) the validation of whether everything went well during the creation of our file.


Performing the Import:



package CreatingFiles; // Defined package.

import java.io.File; // Import the File class 
import java.io.IOException; // Import the IOException class


Step 3: Creating the file.

With the imported classes, we already have everything we need. Now, within our class, we will define the path where we want to create our file:

File file = new File("C:/Users/AcademicoTech/file.txt");

And now, we will actually occupy this memory space by creating our file in the provided directory. To do this, we will use TRY/CATCH to validate if the file creation process occurred as expected. Like this:


try {
    file.createNewFile();
    System.out.print("File created successfully!");
} catch (IOException e) {
    e.printStackTrace();
}

This way, Java will try to create the file. If the operation is successful, the message "File created successfully!" will be displayed. Otherwise, the system's default message will be displayed with the reason why the file creation failed.



Thus, our complete code looks as follows:


package CreatingFiles;

import java.io.File;
import java.io.IOException;

public class CreatingTxtFile {
public static void main(String[] args) {
File file = new File("C:/Users/AcademicoTech/file.txt");
	
   try {
          file.createNewFile();
          System.out.print("File created successfully!");
    } catch (IOException e) {
             e.printStackTrace();
          }
     }
}

Very simple, don't you agree? I hope I have helped in some way. Below are some tips for more posts related to this content!



Como está o seu currículo?

Ter um bom currículo é uma fator chave para você ter seu trabalho reconhecido perante o mercado de trabalho.

 

Sabemos que elaborar um bom currículo que descreva bem suas habilidade e suas expectativas pode ser uma tarefa muito complicada.

Clique no botão abaixo para ter todo o suporte necessário na elaboração de um currículo nota 10.

Como está o seu currículo?

Ter um bom currículo é uma fator chave para você ter seu trabalho reconhecido perante o mercado de trabalho.

 

Sabemos que elaborar um bom currículo que descreva bem suas habilidade e suas expectativas pode ser uma tarefa muito complicada.

Clique no botão abaixo para ter todo o suporte necessário na elaboração de um currículo nota 10.

Sobre o Autor

"Olá meu nome é Tiago Stasaitis, sou formado

Técnico em Informática e bacharel em Sistemas de Informação.

   

Fundei o Acadêmico Tech no intuito de compartilhar conteúdo que pode ajudar pessoas a se desenvolverem pessoal e profissionalmente. "

1633903387510.jpg
  • LinkedIn - Black Circle
  • Instagram

Click here to access our website's Privacy Policy.

bottom of page