Atualização de arquivo em Java

Estamos examinando como atualizar arquivos txt – Csv e JSON em Java com exemplos .



Atualização de arquivo Java - txt

Na atualização do arquivo java , podemos substituir qualquer palavra em um arquivo txt em sua primeira ocorrência usando o método replace() dos métodos String:

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
import java.io.*;
public class Main {
public static void main(String[] args) {
try {
// Read the file into a String
FileReader fr = new FileReader("FirstFile.txt");
BufferedReader mrx = new BufferedReader(fr); // helps in efficient reading of data from a file
StringBuilder ample = new StringBuilder(); // less time is taken to read the file
String line;
while ((line = mrx.readLine()) != null) {
ample.append(line);
ample.append(System.lineSeparator());
}
String replace_word = ample.toString();
mrx.close();
fr.close();
// Replace the specific word with the new word
replace_word = replace_word.replace("Hey", "Greetings");
// Write the modified content back to the file
FileWriter fw = new FileWriter("FirstFile.txt");
fw.write(replace_word);
fw.close();
System.out.println("File updated successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

O mesmo objetivo também pode ser alcançado criando um método uma vez e chamando-o quantas vezes quisermos:

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
import java.io.*;
public class Main {
public static void replace_word(String match_word,String new_word){
try {
// Read the file into a String
FileReader fr = new FileReader("FirstFile.txt");
BufferedReader mrx = new BufferedReader(fr); // helps in efficient reading of data from a file
StringBuilder ample = new StringBuilder(); // less time is taken to read the file
String line;
while ((line = mrx.readLine()) != null) {
ample.append(line);
ample.append(System.lineSeparator());
}
String replace_word = ample.toString();
mrx.close();
fr.close();
// Replace the specific word with the new word
replace_word = replace_word.replace(match_word,new_word);
// Write the modified content back to the file
FileWriter fw = new FileWriter("FirstFile.txt");
fw.write(replace_word);
fw.close();
System.out.println("File updated successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
replace_word("Greetings","Hello User");
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Da mesma forma, também podemos substituir todas as mesmas palavras em um arquivo txt combinando-o com qualquer String específica, usando o método replaceAll() de Java Strings .

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
import java.io.*;
public class Main {
public static void main(String[] args) {
try {
// Read the file into a String
FileReader fr = new FileReader("FirstFile.txt");
BufferedReader mrx = new BufferedReader(fr); // helps in efficient reading of data from a file
StringBuilder ample = new StringBuilder(); // less time is taken to read the file
String line;
while ((line = mrx.readLine()) != null) {
ample.append(line);
ample.append(System.lineSeparator());
}
String replace_word = ample.toString();
mrx.close();
fr.close();
// Replace the specific word with the new word
replace_word = replace_word.replaceAll("we", "you");
// Write the modified content back to the file
FileWriter fw = new FileWriter("FirstFile.txt");
fw.write(replace_word);
fw.close();
System.out.println("File updated successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

De maneira semelhante, também podemos criar um método para corresponder a uma string e substituir todas as palavras correspondentes do arquivo.

Aqui criamos um método chamado replace_word_multiple_times() para substituir várias palavras em um 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
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import java.io.*;
public class Main {
public static void replace_word_multiple_times(String file_name,String word_match,String new_word){
try {
// Read the file into a String
FileReader fr = new FileReader(file_name);
BufferedReader mrx = new BufferedReader(fr); // helps in efficient reading of data from a file
StringBuilder ample = new StringBuilder(); // less time is taken to read the file
String line;
while ((line = mrx.readLine()) != null) {
ample.append(line);
ample.append(System.lineSeparator());
}
String replace_word = ample.toString();
mrx.close();
fr.close();
// Replace the specific word with the new word
replace_word = replace_word.replace(word_match,new_word);
// Write the modified content back to the file
FileWriter fw = new FileWriter(file_name);
fw.write(replace_word);
fw.close();
System.out.println("File updated successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
replace_word_multiple_times("FirstFile.txt","you","We");
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Atualização de arquivo Java - CSV

Também podemos atualizar o conteúdo do arquivo .csv conforme mostrado nos exemplos abaixo.

Para modificar uma palavra em sua primeira ocorrência siga 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
29
30
31
32
33
34
35
36
import java.io.*;
public class Main {
public static void main(String[] args) {
try {
// Read the file into a String
FileReader fr = new FileReader("NewFile.csv");
BufferedReader mrx = new BufferedReader(fr); // helps in efficient reading of data from a file
StringBuilder ample = new StringBuilder(); // less time is taken to read the file
String line;
while ((line = mrx.readLine()) != null) {
ample.append(line);
ample.append(System.lineSeparator());
}
String replace_word = ample.toString();
mrx.close();
fr.close();
// Replace the specific word with the new word
replace_word = replace_word.replace("writing", "declaring");
// Write the modified content back to the file
FileWriter fw = new FileWriter("NewFile.csv");
fw.write(replace_word);
fw.close();
System.out.println("File updated successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Da mesma forma, também podemos modificar todas as mesmas palavras em um arquivo .csv depois de combiná-las todas:

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
import java.io.*;
public class Main {
public static void main(String[] args) {
try {
// Read the file into a String
FileReader fr = new FileReader("NewFile.csv");
BufferedReader mrx = new BufferedReader(fr); // helps in efficient reading of data from a file
StringBuilder ample = new StringBuilder(); // less time is taken to read the file
String line;
while ((line = mrx.readLine()) != null) {
ample.append(line);
ample.append(System.lineSeparator());
}
String replace_word = ample.toString();
mrx.close();
fr.close();
// Replace the specific word with the new word
replace_word = replace_word.replaceAll("we", "you");
// Write the modified content back to the file
FileWriter fw = new FileWriter("NewFile.csv");
fw.write(replace_word);
fw.close();
System.out.println("File updated successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Agora, para fazer isso funcionar de forma mais eficiente, vamos criar métodos chamados replace_word_multiple_times()  e replace_word_single_time() conforme mostrado 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
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
63
64
65
66
67
68
69
70
71
import java.io.*;
public class Main {
public static void replace_word_multiple_times(String file_name,String word_match,String new_word) {
try {
// Read the file into a String
FileReader fr = new FileReader(file_name);
BufferedReader mrx = new BufferedReader(fr); // helps in efficient reading of data from a file
StringBuilder ample = new StringBuilder(); // less time is taken to read the file
String line;
while ((line = mrx.readLine()) != null) {
ample.append(line);
ample.append(System.lineSeparator());
}
String replace_word = ample.toString();
mrx.close();
fr.close();
// Replace the specific word with the new word
replace_word = replace_word.replace(word_match, new_word);
// Write the modified content back to the file
FileWriter fw = new FileWriter(file_name);
fw.write(replace_word);
fw.close();
System.out.println("Replacing all words after matching File updated successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void replace_word_single_time(String file_name,String word_match,String new_word){
try {
// Read the file into a String
FileReader fr = new FileReader(file_name);
BufferedReader mrx = new BufferedReader(fr); // helps in efficient reading of data from a file
StringBuilder ample = new StringBuilder(); // less time is taken to read the file
String line;
while ((line = mrx.readLine()) != null) {
ample.append(line);
ample.append(System.lineSeparator());
}
String replace_word = ample.toString();
mrx.close();
fr.close();
// Replace the specific word with the new word
replace_word = replace_word.replace(word_match,new_word);
// Write the modified content back to the file
FileWriter fw = new FileWriter(file_name);
fw.write(replace_word);
fw.close();
System.out.println("Word changed at first occurrence File updated successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
replace_word_single_time("NewFile.csv","Hey","Hey learner ");
replace_word_multiple_times("NewFile.csv","you","We");
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

 


Atualização de arquivo Java – JSON

Também podemos atualizar os dados do arquivo .json conforme os exemplos abaixo.

Para modificar uma palavra em sua primeira ocorrência siga 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
29
30
31
32
33
34
35
36
import java.io.*;
public class Main {
public static void main(String[] args) {
try {
// Read the file into a String
FileReader fr = new FileReader("NewFile.json");
BufferedReader mrx = new BufferedReader(fr); // helps in efficient reading of data from a file
StringBuilder ample = new StringBuilder(); // less time is taken to read the file
String line;
while ((line = mrx.readLine()) != null) {
ample.append(line);
ample.append(System.lineSeparator());
}
String replace_word = ample.toString();
mrx.close();
fr.close();
// Replace the specific word with the new word
replace_word = replace_word.replace("Java Programming Language", "Java Programming");
// Write the modified content back to the file
FileWriter fw = new FileWriter("NewFile.json");
fw.write(replace_word);
fw.close();
System.out.println("File updated successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Da mesma forma, também podemos modificar várias palavras em um arquivo .json depois de combiná-las e substituí-las usando o método replaceAll() :

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
import java.io.*;
public class Main {
public static void main(String[] args) {
try {
// Read the file into a String
FileReader fr = new FileReader("NewFile.json");
BufferedReader mrx = new BufferedReader(fr); // helps in efficient reading of data from a file
StringBuilder ample = new StringBuilder(); // less time is taken to read the file
String line;
while ((line = mrx.readLine()) != null) {
ample.append(line);
ample.append(System.lineSeparator());
}
String replace_word = ample.toString();
mrx.close();
fr.close();
// Replace the specific word with the new word
replace_word = replace_word.replaceAll("Java", "_Java_");
// Write the modified content back to the file
FileWriter fw = new FileWriter("NewFile.json");
fw.write(replace_word);
fw.close();
System.out.println("File updated successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Aqui, criamos dois métodos diferentes – um para atualizar a primeira ocorrência de palavra correspondente e o segundo para todas as palavras correspondentes em um arquivo JSON :

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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import java.io.*;
public class Main {
public static void replace_word_multiple_times(String file_name,String word_match,String new_word) {
try {
// Read the file into a String
FileReader fr = new FileReader(file_name);
BufferedReader mrx = new BufferedReader(fr); // helps in efficient reading of data from a file
StringBuilder ample = new StringBuilder(); // less time is taken to read the file
String line;
while ((line = mrx.readLine()) != null) {
ample.append(line);
ample.append(System.lineSeparator());
}
String replace_word = ample.toString();
mrx.close();
fr.close();
// Replace the specific word with the new word
replace_word = replace_word.replace(word_match, new_word);
// Write the modified content back to the file
FileWriter fw = new FileWriter(file_name);
fw.write(replace_word);
fw.close();
System.out.println("Replacing all words after matching File updated successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void replace_word_single_time(String file_name,String word_match,String new_word){
try {
// Read the file into a String
FileReader fr = new FileReader(file_name);
BufferedReader mrx = new BufferedReader(fr); // helps in efficient reading of data from a file
StringBuilder ample = new StringBuilder(); // less time is taken to read the file
String line;
while ((line = mrx.readLine()) != null) {
ample.append(line);
ample.append(System.lineSeparator());
}
String replace_word = ample.toString();
mrx.close();
fr.close();
// Replace the specific word with the new word
replace_word = replace_word.replace(word_match,new_word);
// Write the modified content back to the file
FileWriter fw = new FileWriter(file_name);
fw.write(replace_word);
fw.close();
System.out.println("Word changed at first occurrence File updated successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
replace_word_single_time("NewFile.json","Developer","Java Developer");
replace_word_multiple_times("NewFile.json","_Java_","Java");
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Agora você sabe como atualizar arquivos Txt, JSON e Csv 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