1

How to transform an .txt file to .csv with Java?

I did a Java project where I read a .txt file, and I need to use their data to create a .csv file, how should I split the data in the variable where the text is, and how do I turn it into an Excel file (csv)?!

public class main {

public static void main(String args[]) {
    File f = main.dialogoDeAbrirArquivo("Abrir...", 
            JFileChooser.FILES_ONLY, false, new FileNameExtensionFilter("Text File", "txt"),null, null);
}

public static File dialogoDeAbrirArquivo(String tituloDaJanela, int selectionMode, boolean acceptAllFileFilterUsed,
        FileNameExtensionFilter filtro, Component componente,File defaltDirectory) {

    UIManager.put("FileChooser.openDialogTitleText", tituloDaJanela);
    final JFileChooser fileChooser = new JFileChooser();
    fileChooser.setFileSelectionMode(selectionMode);
    fileChooser.setAcceptAllFileFilterUsed(acceptAllFileFilterUsed);
    fileChooser.setCurrentDirectory(defaltDirectory);

    Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
    int x = (dim.width - fileChooser.getSize().width) / 2;
    int y = (dim.height - fileChooser.getSize().height) / 2;
    fileChooser.setLocation(x, y);

    fileChooser.addChoosableFileFilter(filtro);

    int retorno = fileChooser.showOpenDialog(componente);
    if (retorno == JFileChooser.APPROVE_OPTION) {
        File arquivo = fileChooser.getSelectedFile();
        System.out.println("Open file: " + arquivo.getName());
        return arquivo;
    }
    return null;
}
M A
  • 65,721
  • 13
  • 123
  • 159

1 Answers1

0

you must consider the content you want to transform; usually, with a simple text, you can arrange a renaming of the file in .csv

otherwise is preferable to use some libraries to create an excel spreadsheet as Apache POI HSSF provides to

with HSSF you can directly work on workbooks, sheets and cells managing your content

in your case, for the simple renaming:

File fo = new File(arquivo+".csv");
FileOutputStream fos = new FileOutputStream(<some path>+"\\"+fo);
PrintWriter write = new PrintWriter(fos);   

write.println(text);
write.close();
Noomak
  • 353
  • 4
  • 18