public void actionPerformed(ActionEvent e) {
if (e.getSource() == guardar) {
archivo = seleccion.getSelectedFile();
if (archivo.getName().endsWith("txt")) {
String documento = textarea.getText();
String mensaje = guardarArchivo(archivo, documento);
if (mensaje != null) {
JOptionPane.showMessageDialog(null, mensaje);
} else {
JOptionPane.showMessageDialog(null, "Archivo no compatible");
}
} else {
JOptionPane.showMessageDialog(null, "Guardar documento de texto");
}
}
}
public String abrirArchivo(File archivo) {
String documento = "";
try {
entrada = new FileInputStream(archivo);
int ascii;
while ((ascii = entrada.read()) != -1) {
char caracter = (char) ascii;
documento += caracter;
}
} catch (Exception e) {
}
return documento;
}
public String guardarArchivo(File archivo, String documento) {
String mensaje = null;
try {
salida = new FileOutputStream(archivo);
byte[] bytxt = documento.getBytes();
salida.write(bytxt);
mensaje = "Archivo guardado";
} catch (Exception e) {
}
return mensaje;
}
}
Solo tengo eso, y si se pyede elegir la ubicacion donde guardar el archivo
Cita de: Beginner Web en 9 Septiembre 2019, 00:02 AM
public void actionPerformed(ActionEvent e) {
if (e.getSource() == guardar) {
archivo = seleccion.getSelectedFile();
if (archivo.getName().endsWith("txt")) {
String documento = textarea.getText();
String mensaje = guardarArchivo(archivo, documento);
if (mensaje != null) {
JOptionPane.showMessageDialog(null, mensaje);
} else {
JOptionPane.showMessageDialog(null, "Archivo no compatible");
}
} else {
JOptionPane.showMessageDialog(null, "Guardar documento de texto");
}
}
}
public String abrirArchivo(File archivo) {
String documento = "";
try {
entrada = new FileInputStream(archivo);
int ascii;
while ((ascii = entrada.read()) != -1) {
char caracter = (char) ascii;
documento += caracter;
}
} catch (Exception e) {
}
return documento;
}
public String guardarArchivo(File archivo, String documento) {
String mensaje = null;
try {
salida = new FileOutputStream(archivo);
byte[] bytxt = documento.getBytes();
salida.write(bytxt);
mensaje = "Archivo guardado";
} catch (Exception e) {
}
return mensaje;
}
}
Solo tengo eso, y si se pyede elegir la ubicacion donde guardar el archivo
Con el listener del item menú, obtén el String y escríbelo.
Puedes usar JFileChooser para escojer la ubicación del archivo final
Tengo ejemplos con JFileChooser por aquí.
PD: cuando manejes excepciones, se más específica, en este caso en vez de usar la clase Exception usa, IOException que se refiere a una posible excepción de lectura/escritura de datos, tanto en tiempo de compilación o runtime.