Ler arquivos em Java

Está sendo realizada uma Discussão sobre Como ler arquivos em Java com exemplos para facilitar o aprendizado.



Leitura de arquivos Java – txt

Você aprendeu como criar e gravar em arquivos no capítulo anterior .

O arquivo de texto que criamos no capítulo anterior é lido usando a classe Scanner no exemplo abaixo.

Mas antes de ler o arquivo, certifique-se de gravar qualquer coisa no arquivo manualmente ou usando o método write() , que foi discutido anteriormente no arquivo java write e create.

Este exemplo ilustra a recuperação de dados de FirstFile.txt que criamos na sessão anterior.

Java Read Files 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
26
import java.io.File; // Import the File class from Java.io package
import java.io.FileNotFoundException; // This class is imported in order to tackle issues
import java.util.Scanner; // Here we imported the Scanner class from java.util Package
public class Main{
public static void main(String[] args) {
try {
File ample = new File("FirstFile.txt");
Scanner mrx_read = new Scanner(ample);
while (mrx_read.hasNextLine()) {
String mrx_data = mrx_read.nextLine();
System.out.println(mrx_data);
}
mrx_read.close();
} catch (FileNotFoundException e){
System.out.println("An Error occurred while reading the file");
e.printStackTrace();
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Arquivos Java Leia o exemplo 1Da mesma forma, se quisermos ler o conteúdo do arquivo SecondFile.txt que criamos anteriormente, siga o exemplo dado:

 

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
import java.io.File; // Import the File class from Java.io package
import java.io.FileNotFoundException; // This class is imported in order to tackle issues
import java.util.Scanner; // Here we imported the Scanner class from java.util Package
public class Main{
public static void main(String[] args) {
try {
File mrx = new File("SecondFile.txt");
Scanner ample_read = new Scanner(mrx);
while (ample_read.hasNextLine()) {
String mrx_data = ample_read.nextLine();
System.out.println(mrx_data);
}
ample_read.close();
} catch (FileNotFoundException e){
System.out.println("An Error occurred while reading the file");
e.printStackTrace();
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Leitura de Arquivos Java – PDF

Podemos também ler o conteúdo do arquivo .pdf que criamos no último post :

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.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
public class PdfToConsole {
public static void main(String args[]) throws IOException {
//Loading an existing document
File file = new File("mrexample\\java\\SecondPdf.pdf");
PDDocument document = PDDocument.load(file);
//Instantiate PDFTextStripper class
PDFTextStripper pdfStripper = new PDFTextStripper();
//Retrieving text from PDF document
String text = pdfStripper.getText(document);
System.out.println(text);
//Closing the document
document.close();
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Arquivos Java ler pdf

 


Leitura de Arquivos Java – CSV

Para ler o arquivo .csv confira os exemplos abaixo:

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
import java.io.File; // Import the File class from Java.io package
import java.io.FileNotFoundException; // This class is imported in order to tackle issues
import java.util.Scanner; // Here we imported the Scanner class from java.util Package
public class Main{
public static void main(String[] args) {
try {
File mrx = new File("NewFile.csv");
Scanner ample_read = new Scanner(mrx);
while (ample_read.hasNextLine()) {
String mrx_data = ample_read.nextLine();
System.out.println(mrx_data);
}
ample_read.close();
} catch (FileNotFoundException e){
System.out.println("An Error occurred while reading the file");
e.printStackTrace();
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Arquivos Java lidos csv


Leitura de arquivos Java – JSON

Da mesma forma, podemos ler o arquivo JSON em Java conforme retratado nos exemplos abaixo:

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
import java.io.File; // Import the File class from Java.io package
import java.io.FileNotFoundException; // This class is imported in order to tackle issues
import java.util.Scanner; // Here we imported the Scanner class from java.util Package
public class Main{
public static void main(String[] args) {
try {
File mrx = new File("NewFile.json");
Scanner ample_read = new Scanner(mrx);
while (ample_read.hasNextLine()) {
String mrx_data = ample_read.nextLine();
System.out.println(mrx_data);
}
ample_read.close();
} catch (FileNotFoundException e){
System.out.println("An Error occurred while reading the file");
e.printStackTrace();
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

 


Obter informações do arquivo

Você pode usar os métodos File em Java Files Read para aprender mais sobre um arquivo.

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
import java.io.File; // Import the File class from Java.io package
public class Main{
public static void main(String[] args) {
File mrx=new File("FirstFile.txt");
if(mrx.exists()){
System.out.println("\nFile name: "+mrx.getName()); // Returns name of the file (FirstFile.txt)
System.out.println("\n"+mrx.getName()+" Absolute Path: "+mrx.getAbsolutePath()); // Returns the location of file in computer
System.out.println("\n"+mrx.getName()+"'s length in bytes: "+mrx.length()); // Gives length of file in bytes
System.out.println("\nIs my file "+mrx.canRead()+" Readable?");
System.out.println("Answer: "+mrx.canRead()); // Shows if file is readable or not
System.out.println("\nCan I write to my file "+mrx.getName()+" ?");
System.out.println("Answer: "+mrx.canWrite()); // Replies true if file can be written else false
System.out.println("\nCan I execute my file "+mrx.getName()+" ?");
System.out.println("Answer: "+mrx.canExecute()); // Returns true is file is executable or otherwise
}
else{
System.out.println("File not Found");
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Da mesma forma, também podemos obter todos os detalhes do arquivo “SecondFile.txt” seguindo o exemplo abaixo:

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
import java.io.File; // Import the File class from Java.io package
public class Main{
public static void main(String[] args) {
File mrx=new File("SecondFile.txt");
if(mrx.exists()){
System.out.println("\nFile name: "+mrx.getName()); // Returns name of the file (FirstFile.txt)
System.out.println("\n"+mrx.getName()+" Absolute Path: "+mrx.getAbsolutePath()); // Returns the location of file in computer
System.out.println("\n"+mrx.getName()+"'s length in bytes: "+mrx.length()); // Gives length of file in bytes
System.out.println("\nIs my file "+mrx.canRead()+" Readable?");
System.out.println("Answer: "+mrx.canRead()); // Shows if file is readable or not
System.out.println("\nCan I write to my file "+mrx.getName()+" ?");
System.out.println("Answer: "+mrx.canWrite()); // Replies true if file can be written else false
System.out.println("\nCan I execute my file "+mrx.getName()+" ?");
System.out.println("Answer: "+mrx.canExecute()); // Returns true is file is executable or otherwise
}
else{
System.out.println("File not Found");
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Também podemos obter os detalhes do arquivo .pdf que criamos acima:

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
import java.io.File; // Import the File class from Java.io package
public class Main{
public static void main(String[] args) {
File mrx=new File("NewFile.pdf");
if(mrx.exists()){
System.out.println("\nFile name: "+mrx.getName()); // Returns name of the file (FirstFile.txt)
System.out.println("\n"+mrx.getName()+" Absolute Path: "+mrx.getAbsolutePath()); // Returns the location of file
System.out.println("\n"+mrx.getName()+"'s length in bytes: "+mrx.length()); // Gives length of file in bytes
System.out.println("\nIs my file "+mrx.canRead()+" Readable?");
System.out.println("Answer: "+mrx.canRead()); // Shows if file is readable or not
System.out.println("\nCan I write to my file "+mrx.getName()+" ?");
System.out.println("Answer: "+mrx.canWrite()); // Replies true if file can be written else false
System.out.println("\nCan I execute my file "+mrx.getName()+" ?");
System.out.println("Answer: "+mrx.canExecute()); // Returns true is file is executable or otherwise
}
else{
System.out.println("File not Found");
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Da mesma forma , podemos obter as informações do arquivo .csv que criamos na sessão anterior usando o método createNewFile() do Java e gravamos nele usando o método write() :

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
import java.io.File; // Import the File class from Java.io package
public class Main{
public static void main(String[] args) {
File mrx=new File("NewFile.csv");
if(mrx.exists()){
System.out.println("\nFile name: "+mrx.getName()); // Returns name of the file (FirstFile.txt)
System.out.println("\n"+mrx.getName()+" Absolute Path: "+mrx.getAbsolutePath()); // Returns the location of file
System.out.println("\n"+mrx.getName()+"'s length in bytes: "+mrx.length()); // Gives length of file in bytes
System.out.println("\nIs my file "+mrx.canRead()+" Readable?");
System.out.println("Answer: "+mrx.canRead()); // Shows if file is readable or not
System.out.println("\nCan I write to my file "+mrx.getName()+" ?");
System.out.println("Answer: "+mrx.canWrite()); // Replies true if file can be written else false
System.out.println("\nCan I execute my file "+mrx.getName()+" ?");
System.out.println("Answer: "+mrx.canExecute()); // Returns true is file is executable or otherwise
}
else{
System.out.println("File not Found");
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Os detalhes do arquivo .json podem ser obtidos de maneira semelhante:

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
import java.io.File; // Import the File class from Java.io package
public class Main{
public static void main(String[] args) {
File mrx=new File("NewFile.json");
if(mrx.exists()){
System.out.println("\nFile name: "+mrx.getName()); // Returns name of the file (FirstFile.txt)
System.out.println("\n"+mrx.getName()+" Absolute Path: "+mrx.getAbsolutePath()); // Returns the location of file
System.out.println("\n"+mrx.getName()+"'s length in bytes: "+mrx.length()); // Gives length of file in bytes
System.out.println("\nIs my file "+mrx.canRead()+" Readable?");
System.out.println("Answer: "+mrx.canRead()); // Shows if file is readable or not
System.out.println("\nCan I write to my file "+mrx.getName()+" ?");
System.out.println("Answer: "+mrx.canWrite()); // Replies true if file can be written else false
System.out.println("\nCan I execute my file "+mrx.getName()+" ?");
System.out.println("Answer: "+mrx.canExecute()); // Returns true is file is executable or otherwise
}
else{
System.out.println("File not Found");
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Lembrete: A API Java fornece uma ampla variedade de classes que podem ser usadas para ler e gravar arquivos em Java . Isso inclui FileWriter , BufferedWriter , FileInputStream , FileOutputStream , Files, Scanner , FileReader , BufferedReader , etc.
Qual deles usar depende da versão do Java que você está usando, se você precisa ler caracteres ou bytes, o comprimento do arquivo/linhas e outros fatores.

Agora você tem uma melhor compreensão do Java Files Read e como ele funciona. Para saber mais sobre como excluir um arquivo em Java, consulte o capítulo Java Excluir arquivos .

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