Java Criar e Gravar Arquivos

Vamos discutir como criar arquivos em Java com exemplos , na esperança de atender aos seus objetivos de aprendizado.



Java Criar Arquivos – TXT

Em relação à criação de arquivo Java , o método createNewFile() pode ser usado para criar um arquivo.

Quando esse método é executado, um valor booleano é retornado: se o arquivo foi criado com sucesso, retorna true , e se já existia, retorna false .

Este artigo ilustra como criar quatro tipos diferentes de arquivos usando o método createnewfile() .

  1. arquivo .txt (arquivo de documento de texto)
  2. arquivo .pdf (formato de documento portátil)
  3. arquivo .csv (formato de valores separados por vírgula)
  4. Arquivo .JSON (JavaScript Object Notation)

Um bloco try-catch envolve o método. Devido ao fato de que um IOException será lançado se houver um erro (se o arquivo não puder ser criado por algum motivo):

Create txt File Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import java.io.File; // File class is imported from the java.io package
import java.io.IOException; // To handle errors, import the IOException class
public class Main {
public static void main(String[] args) {
try {
File mrx_Obj = new File("FirstFile.txt");
if (mrx_Obj.createNewFile()) {
System.out.println("File is Successfully created: " + mrx_Obj.getName());
} else {
System.out.println("The File "+mrx_Obj.getName()+" already exists");
}
} catch (IOException e) {
System.out.println("An error has generated during the creation of the file");
e.printStackTrace();
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

 

Java Criar exemplos de arquivo txt

Create txt File Example:2 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import java.io.File;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
File ample_Obj=new File("SecondFile.txt");
if (ample_Obj.createNewFile()){
System.out.println("New File is created : "+ample_Obj.getName());
}
else {
System.out.println(ample_Obj.getName()+" file already exists in the directory");
}
}
catch (IOException e){
System.out.println("An error occurred while creating file");
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

A criação de arquivos Java em um diretório específico requer a especificação do caminho e o escape do caractere “” por barras invertidas duplas (para Windows).

Por outro lado, você pode apenas escrever o caminho, como: /Users/name/filename.txt, em Macs e Linux.

Create txt File Example:3 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import java.io.File;
import java.io.IOException;
public class Main{
public static void main(String[] args) {
try {
File myObj = new File("mrexample\\java\\NewFile.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
System.out.println("Absolute path: " + myObj.getAbsolutePath());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

 

Create txt File Example:4 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import java.io.File;
import java.io.IOException;
public class Main{
public static void main(String[] args) {
try {
File myObj = new File("mrexample\\java\\AnotherFile.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
System.out.println("Absolute path: " + myObj.getAbsolutePath());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

 


Java Criar Arquivo PDF

Um arquivo de documento portátil pode ser facilmente criado adicionando uma extensão de (.pdf) ao nome do arquivo usando o método createNewFile() do java.

Os exemplos dados irão ensiná-lo a criar um arquivo pdf facilmente:

Create PDF File Example:1 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import java.io.File;
import java.io.IOException; // Handles the exceptions during the creation of file
import org.apache.pdfbox.pdmodel.PDDocument; // Create Template of Pdf files
import org.apache.pdfbox.pdmodel.PDPage; // Create Border,Model of the Pdf file
public class Main{
public static void main(String args[]) throws IOException
{
PDDocument mrx_pdf= new PDDocument();
mrx_pdf.addPage(new PDPage()); // A builtin method to add pages to the created pdf
// Saves the file FirstPdf to the system
mrx_pdf.save("FirstPdf.pdf");
// Prints the message upon successful creation of pdf file
System.out.println("The PDF file is successfully created by the name FirstPdf.pdf");
// document should be closed after being created
mrx_pdf.close();
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

 

Também podemos criar o arquivo .pdf em qualquer pasta ou diretório específico, conforme exemplos abaixo:

Aqui criamos o arquivo .pdf no diretório público usando o método createNewFile() do java :

Create PDF File Example:2 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Main{
public static void main(String args[]) throws IOException
{
PDDocument mrx_pdf= new PDDocument();
mrx_pdf.addPage(new PDPage()); // A builtin method to add pages to the created pdf
// Shows the path of the PDF file
mrx_pdf.save("mrexample\\java\\NewFile.pdf");
// Prints the message upon successful creation of pdf file
System.out.println("The PDF file is successfully created by the name My_NewPDF");
// document should be closed after being created
mrx_pdf.close();
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

 


Java Criar Arquivo CSV

O arquivo de valor separado por vírgula pode ser facilmente criado adicionando uma extensão de ( .csv ) ao nome do arquivo ao implementar o método createNewFile() do java.

Os exemplos fornecidos irão guiá-lo como fazê-lo facilmente:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import java.io.File; // File class is imported from the java.io package
import java.io.IOException; // To handle errors, import the IOException class
public class Main {
public static void main(String[] args) {
try {
File ample_csv = new File("MyFirstCsvFile.csv");
if (ample_csv.createNewFile()) {
System.out.println("Csv File is Successfully created: " + ample_csv.getName());
} else {
System.out.println("The File "+ample_csv.getName()+" already exists");
}
} catch (IOException e) {
System.out.println("An error has generated during the creation of the file");
e.printStackTrace();
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import java.io.File; // File class is imported from the java.io package
import java.io.IOException; // To handle errors, import the IOException class
public class Main {
public static void main(String[] args) {
try {
File ample_csv = new File("MySecondCsvFile.csv");
if (ample_csv.createNewFile()) {
System.out.println("Csv File is Successfully created: " + ample_csv.getName());
} else {
System.out.println("The File "+ample_csv.getName()+" already exists");
}
} catch (IOException e) {
System.out.println("An error has generated during the creation of the file");
e.printStackTrace();
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

O exemplo dado mostra a criação do arquivo .csv no diretório público usando o método createNewFile() do Java :

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import java.io.File;
import java.io.IOException;
public class Main{
public static void main(String[] args) {
try {
File myObj = new File("mrexample\\java\\NewFile.csv");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
System.out.println("Absolute path: " + myObj.getAbsolutePath());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

 


Java Criar arquivo JSON

O arquivo Java Script Object Notation pode ser formado de forma semelhante adicionando a extensão .json ao nome do arquivo ao construí-lo usando o método java createNewFile() :

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import java.io.File; // File class is imported from the java.io package
import java.io.IOException; // To handle errors, import the IOException class
public class Main {
public static void main(String[] args) {
try {
File mrx_json = new File("MyFirstJSONFile.json");
if (mrx_json.createNewFile()) {
System.out.println("First JSON File is Successfully created named : " + mrx_json.getName());
} else {
System.out.println("The File "+mrx_json.getName()+" already exists");
}
} catch (IOException e) {
System.out.println("An error has generated during the creation of the file");
e.printStackTrace();
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import java.io.File; // File class is imported from the java.io package
import java.io.IOException; // To handle errors, import the IOException class
public class Main {
public static void main(String[] args) {
try {
File ample_json= new File("MySecondJSONFile.json");
if (ample_json.createNewFile()) {
System.out.println("Another JSON File is Successfully created named : " + ample_json.getName());
} else {
System.out.println("The File "+ample_json.getName()+" already exists");
}
} catch (IOException e) {
System.out.println("An error has generated during the creation of the file");
e.printStackTrace();
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Um arquivo de extensão .json pode ser criado em um diretório público usando o método createNewFile() do Java , conforme mostrado no exemplo a seguir:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import java.io.File;
import java.io.IOException;
public class Main{
public static void main(String[] args) {
try {
File myObj = new File("mrexample\\java\\NewFile.json");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
System.out.println("Absolute path: " + myObj.getAbsolutePath());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

 


Gravar arquivo TXT em Java

Para escrever algum texto no arquivo que criamos acima, usamos a classe FileWriter e seu método write() .

Em Java create files , você deve fechar o arquivo após terminar de escrever.

Escrevemos e fechamos os arquivos posteriormente, que foram criados nos exemplos de criação de arquivo em um diretório específico acima.

No exemplo abaixo, escrevemos com sucesso no arquivo .txt :

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.io.File;
import java.io.FileWriter; // The FileWriter class from the java.io package is imported here
import java.io.IOException; // The errors can be handled by importing the IO.Exception class
public class Main{
public static void main(String[] args) {
try {
File ample=new File("FirstFile.txt");
FileWriter mrx_write=new FileWriter("FirstFile.txt");
mrx_write.write("Hey ! we are writing this sentence to the First File we create");
mrx_write.close();
System.out.println("The file: "+ample.getName()+" is successfully written and closed");
} catch (IOException e) {
System.out.println("An error is generated while writing to the file");
e.printStackTrace();
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import java.io.File;
import java.io.FileWriter; // The FileWriter class from the java.io package is imported here
import java.io.IOException; // The errors can be handled by importing the IO.Exception class
public class Main{
public static void main(String[] args) {
try {
File ample=new File("SecondFile.txt");
FileWriter mrx_write=new FileWriter("SecondFile.txt");
mrx_write.write("Hey !\nWe are learning how to write to a file \nIn this programme we are writing the text to the File"+ample.getName()+" using the write method \nAnd will close it using the close() method");
mrx_write.close();
System.out.println("The file: "+ample.getName()+" is successfully written and closed");
} catch (IOException e) {
System.out.println("An error is generated while writing to the file");
e.printStackTrace();
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Escrever arquivo PDF em Java

Da mesma forma, também podemos gravar no arquivo .pdf que criamos acima no diretório público:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
public class GeneratePdf
{
public static void main(String args[])
{
//created PDF document instance
Document doc = new Document();
try
{
//generate a PDF at the specified location
PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream("mrexample\\java\\SecondPdf.pdf"));
System.out.println("Your pdf is created successfully.");
//opens the PDF
doc.open();
//adds paragraph to the PDF file
doc.add(new Paragraph("We are writing this sentence to the SecondPdf.pdf file"));
//close the PDF file
doc.close();
System.out.println("Your pdf is written and closed successfully.");
//closes the writer
writer.close();
}
catch (DocumentException e)
{
e.printStackTrace();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

 


Gravar arquivo CSV em Java

O exemplo fornecido mostra o método de gravação em um arquivo .csv :

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.io.File;
import java.io.FileWriter; // The FileWriter class from the java.io package is imported here
import java.io.IOException; // The errors can be handled by importing the IO.Exception class
public class Main{
public static void main(String[] args) {
try {
File ample=new File("NewFile.csv");
FileWriter mrx_write=new FileWriter("NewFile.csv");
mrx_write.write("Hey ! we are writing this sentence to the Csv file we created");
mrx_write.close();
System.out.println("The file: "+ample.getName()+" is successfully written and closed");
} catch (IOException e) {
System.out.println("An error is generated while writing to the file");
e.printStackTrace();
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Gravar arquivo JSON em Java

O exemplo a seguir mostra como gravar em um arquivo JSON :

Write Json File Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.io.File;
import java.io.FileWriter; // The FileWriter class from the java.io package is imported here
import java.io.IOException; // The errors can be handled by importing the IO.Exception class
public class Main{
public static void main(String[] args) {
try {
File ample=new File("NewFile.json");
FileWriter mrx_write=new FileWriter("NewFile.json");
mrx_write.write("[{'Title': 'Developer',\n 'Programming Language': 'Java Programming Language', \n 'isJavaEasy': 'true'}]");
mrx_write.close();
System.out.println("The file: "+ample.getName()+" is successfully written and closed");
} catch (IOException e) {
System.out.println("An error is generated while writing to the file");
e.printStackTrace();
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

 


Para obter mais informações sobre a leitura dos arquivos acima, consulte o artigo sobre leitura de arquivos em Java .

Nós valorizamos o seu feedback.
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Assine a nossa newsletter
Digite seu e-mail para receber um resumo semanal de nossos melhores posts. Saber mais!
ícone