elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: (TUTORIAL) Aprende a emular Sentinel Dongle By Yapis


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  Java
| | | |-+  JFileChooser guardar un archivo con nombre preterminado
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: JFileChooser guardar un archivo con nombre preterminado  (Leído 3,557 veces)
SrTrp


Desconectado Desconectado

Mensajes: 325


Script/C#


Ver Perfil
JFileChooser guardar un archivo con nombre preterminado
« en: 22 Noviembre 2018, 06:38 am »

Quiero guardar un archivo con un nombre predeterminado por ejemplo hola.bat, hola.txt y con la extensión que quiera pero al abrir el filechosser se elija la ruta de donde quiera guardarlo
Código
  1.            String direc = "";
  2.            try{
  3.            if(jfc.showSaveDialog(null)==jfc.APPROVE_OPTION){
  4.            direc = jfc.getSelectedFile().getAbsolutePath();
  5.  
  6.                File archivo = new File(direc);
  7.                 FileWriter ec = new FileWriter(archivo);
  8.                 ec.write("HOLAAAAAAAAAAA");                
  9.                 ec.close();
  10.  
  11.            }
  12.            }catch (Exception ex){
  13.            ex.printStackTrace();
  14.            }
  15.  


En línea

rub'n


Desconectado Desconectado

Mensajes: 1.217


(e -> λ("live now")); tatuar -> λ("α");


Ver Perfil WWW
Re: JFileChooser guardar un archivo con nombre preterminado
« Respuesta #1 en: 22 Noviembre 2018, 11:04 am »

Hola,

Es mejor usar alguna clase que contenga un buffer interno algo mas grande para que la escritura lectura sea mas eficiente, BufferedWriter posser un buffer por default de 8192 bytes, mientras que FileWrite es de 1024bytes, aunque pues también funciona.


  • la line 23, se usa try-with-resources, usado en clases que implementen a AutoCloseable, evitando usar .close()
  • El método getTexto() se le concatenan saltos de linea, para crear un .bat con \r\n
  • Si vas escribir solo texto pues es mas fácil aun
  • En la linea 25, puedes Usar APPEND por CREATE, para insertar texto al final del archivo, sin borrar nada

Código
  1. package foro;
  2.  
  3. import javax.swing.*;
  4. import java.io.BufferedWriter;
  5. import java.io.IOException;
  6. import java.nio.file.Files;
  7. import java.nio.file.Path;
  8. import java.nio.file.Paths;
  9. import java.nio.file.StandardOpenOption;
  10. /**
  11.  * @author rub´n
  12.  */
  13. public class TestFileChooser {
  14.  
  15.    public TestFileChooser() {
  16.  
  17.    }
  18.  
  19.    public void EscribirEnArchivo(final String texto) {
  20.        //Async manera [b]sucia[/b]
  21.        new Thread(() -> {
  22.            //getDest() obtiene el path absoluto + se concatena con el nombre del archivo
  23.            final Path directorio = Paths.get(getDest().toString() + "/TuNombreDeArchivo.bat");
  24.            final StringBuilder sb = new StringBuilder();
  25.            try(final BufferedWriter bW = Files.newBufferedWriter(directorio,StandardOpenOption.CREATE)) {
  26.                bW.write(sb.append(texto).toString());
  27.                JOptionPane.showMessageDialog(null,"Escritura Lista");
  28.            } catch (IOException e) {
  29.                e.printStackTrace();
  30.            }
  31.        }).start();
  32.    }
  33.  
  34.    //Obtener destino
  35.    private Path getDest() {
  36.        final JFileChooser jFileChooser = new JFileChooser();
  37.        jFileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
  38.        //jFileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); en este caso a ti te sirve escojer el directorio
  39.  
  40.        final int opc = jFileChooser.showOpenDialog(null);
  41.        if (!(opc == 0)) {
  42.            System.exit(0);
  43.        }
  44.        return jFileChooser.getSelectedFile().toPath();
  45.    }
  46.  
  47.    private static String getTexto() {
  48.        final StringBuilder sb = new StringBuilder();
  49.        return sb.append("@echo off\r\n")
  50.                .append("msg * Hola SrTrp\r\n")
  51.                .append(":end")
  52.                .toString();
  53.    }
  54.  
  55.    public static void main(String... _0x72) {
  56.        try {
  57.            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
  58.        } catch (Exception ex){ex.printStackTrace();}
  59.        final TestFileChooser testFileChooser = new TestFileChooser();
  60.        testFileChooser.EscribirEnArchivo(getTexto());
  61.    }
  62. }
  63.  


« Última modificación: 8 Junio 2019, 15:32 pm por rub'n » En línea



rubn0x52.com KNOWLEDGE  SHOULD BE FREE.
If you don't have time to read, you don't have the time (or the tools) to write, Simple as that. Stephen ki
Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Guardar .txt con nombre aleatorio (¿random?)
Programación Visual Basic
ubetor^^ 5 4,456 Último mensaje 11 Octubre 2006, 23:58 pm
por vivachapas
Guardar contenido de un textbox en un archivo .txt con nombre aletorio
Programación Visual Basic
hepy_92 2 4,097 Último mensaje 15 Abril 2007, 20:15 pm
por hepy_92
Problema al guardar nombre de archivo en variable (batch) SOLUCIONADO
Scripting
<ИΘZIЭ(ŦB> 8 10,905 Último mensaje 22 Septiembre 2009, 01:12 am
por Aranguez
JFileChooser
Java
alzehimer_cerebral 8 12,888 Último mensaje 30 Mayo 2012, 08:28 am
por Proteus1989
jFilechooser como guardar en una ruta
Java
ivanrodas 1 2,814 Último mensaje 19 Mayo 2014, 10:26 am
por ivanrodas
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines