forked from googleworkspace/java-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEscreverLerArquivo
62 lines (44 loc) · 1.4 KB
/
EscreverLerArquivo
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package dib;
import java.io.*;
public class EscreverLerArquivo {
public static void main(String[] args) {
try {
// Conteudo do arquivo
String content = "Teste";
String nomeArquivo = "teste.txt";
createFile(content, nomeArquivo);
readFile(nomeArquivo);
System.out.println("----- Feito! ------");
} catch (IOException e) {
e.printStackTrace();
}
}
private static void createFile(String content, String nomeArquivo){
try {
// Cria arquivo
File file = new File("c:/temp/" + nomeArquivo);
// Se o arquivo nao existir, ele gera
if (!file.exists()) {
file.createNewFile();
}
// Prepara para escrever no arquivo
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
// Escreve e fecha arquivo
bw.write(content);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void readFile(String nomeArquivo) throws FileNotFoundException, IOException {
// Le o arquivo
FileReader ler = new FileReader("c:/temp/" + nomeArquivo);
BufferedReader reader = new BufferedReader(ler);
String linha;
while( (linha = reader.readLine()) != null ){
System.out.println(linha);
}
reader.close();
}
}