-
Notifications
You must be signed in to change notification settings - Fork 122
Expand file tree
/
Copy pathFileManager.java
More file actions
54 lines (49 loc) · 1.62 KB
/
FileManager.java
File metadata and controls
54 lines (49 loc) · 1.62 KB
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
package simplejavatexteditor;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
/**
* [REFACTORING 2] Extract Class:
* Esta clase asume la responsabilidad de leer y escribir archivos
* liberando a la UI de estas tareas (Principio SRP).
*/
public class FileManager {
// Método para leer contenido (usado en Drag & Drop)
public String readContent(String fileName) {
String content = "";
try (FileInputStream fis = new FileInputStream(new File(fileName))) {
byte[] ba = new byte[fis.available()];
fis.read(ba);
content = new String(ba);
} catch (Exception ex) {
ex.printStackTrace();
}
return content;
}
// Método para abrir archivos de texto normales
public String openFile(File file) {
String content = "";
try (Scanner scan = new Scanner(new FileReader(file))) {
StringBuilder sb = new StringBuilder();
while (scan.hasNext()) {
sb.append(scan.nextLine()).append("\n");
}
content = sb.toString();
} catch (Exception ex) {
System.err.println(ex.getMessage());
}
return content;
}
// Método para guardar archivos
public void saveFile(File file, String content) {
try (BufferedWriter out = new BufferedWriter(new FileWriter(file))) {
out.write(content);
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
}
}