使用Java导出到.csv不会输出文件 [英] Export to .csv using java does not output file

查看:68
本文介绍了使用Java导出到.csv不会输出文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将JTable的内容导出到.csv文件.我尝试了一些代码,没有错误,但是我要写入的文件没有被写入.有人知道为什么吗?谢谢

 公共静态布尔值exportToCSV(JTable resultsTable){尝试 {TableModel模型= resultsTable.getModel();FileWriter csv = new FileWriter(new File("/tmp/export.csv"));for(int i = 0; i< model.getColumnCount(); i ++){csv.write(model.getColumnName(i)+,");}csv.write("\ n");for(int i = 0; i< model.getRowCount(); i ++){for(int j = 0; j< model.getColumnCount(); j ++){csv.write(model.getValueAt(i,j).toString()+,");}csv.write("\ n");}csv.close();返回true;} catch(IOException e){e.printStackTrace();}返回false;} 

解决方案

带有简单文件的实践

采取婴儿步骤.首先,请确保您成功打开文件.

现代Java提供了 路径

使用CSV格式的库

接下来,对于CSV或制表符分隔的文件等,请使用库.我使用 Apache Commons CSV .搜索堆栈溢出中有许多使用此库和其他此类库来读写此类文件的示例.

使用 CSVFormat 定义文件的类型.在这里,我们使用由 RFC 4180 定义的标准CSV.请注意,标准CSV使用CRLF(回车行进给)表示换行符,而不是在类Unix平台中常见的LF(换行).

打开文件时,我们指定 UTF-8 字符编码.通常,UTF-8是最好的编码方式.它涵盖所有Unicode字符,并且是 US-ASCII 的超集.

CSVPrinter :: print 方法在输出一行时一次添加一个字段.我们通过调用 CSVPrinter :: println 终止行.

我将您的 i 重命名为& j 变量才有意义.

我在文件顶部添加了列名.您可能要保留或放弃该功能,完全由您决定.

注意我们如何使用try-with-resources语法自动关闭文件.

 包work.basil.example;导入org.apache.commons.csv.CSVFormat;导入org.apache.commons.csv.CSVPrinter;导入org.apache.commons.csv.CSVRecord;导入javax.swing.*;导入javax.swing.table.TableModel;导入java.io.BufferedWriter;导入java.io.IOException;导入java.nio.charset.StandardCharsets;导入java.nio.file.Files;导入java.nio.file.Path;导入java.nio.file.Paths;公共类Csver{公共静态void主(String [] args){Csver应用=新的Csver();//练习编写一个简单的文件.app.writeDummyFile();//将JTable中的数据写到标准CSV文件中.JTable jtable = app.newJTable();app.writeCSV(jtable.getModel());System.out.println(«fin»");}private void writeCSV(最终的TableModel模型){CSVFormat格式= CSVFormat.RFC4180;路径path = Paths.get("/Users/basilbourque/animals.csv");尝试 (BufferedWriter writer = Files.newBufferedWriter(path,StandardCharsets.UTF_8);CSVPrinter printer =新的CSVPrinter(writer,format);){//打印列标题(如果需要).for(int columnIndex = 0; columnIndex< model.getColumnCount(); columnIndex ++){printer.print(model.getColumnName(columnIndex));}printer.println();//打印行.for(int rowIndex = 0; rowIndex< model.getRowCount(); rowIndex ++){for(int columnIndex = 0; columnIndex< model.getColumnCount(); columnIndex ++){printer.print(model.getValueAt(rowIndex,columnIndex));}printer.println();}} catch(IOException e){e.printStackTrace();}}私人JTable newJTable(){String [] columnNames = {"Species","Name"};Object [] [] data = {{"Dog","Delilah"},{"Cat",René"},{"Bird","Jordan"}};JTable表=新的JTable(data,columnNames);退货表;}私有无效writeDummyFile(){路径path = Paths.get("/Users/basilbourque/dummy.txt");//如果成功打开文件,请使用try-with-resources自动关闭文件.试试(BufferedWriter writer = Files.newBufferedWriter(path)){writer.write("Bonjour le monde!");} catch(IOException e){e.printStackTrace();}}} 

I am trying to export content of a JTable to a .csv file. I tried some code, there is no error but the file I intended to write does not get written. Could anyone see why? Thanks

public static boolean exportToCSV(JTable resultsTable) {
   try {

    TableModel model = resultsTable.getModel();
    FileWriter csv = new FileWriter(new File("/tmp/export.csv"));

    for (int i = 0; i < model.getColumnCount(); i++) {
        csv.write(model.getColumnName(i) + ",");
    }

    csv.write("\n");

    for (int i = 0; i < model.getRowCount(); i++) {
        for (int j = 0; j < model.getColumnCount(); j++) {
            csv.write(model.getValueAt(i, j).toString() + ",");
        }
        csv.write("\n");
    }

    csv.close();
    return true;
   } catch (IOException e) {
    e.printStackTrace();
   }
   return false;
}

解决方案

Practice with a simple file

Take baby steps. First, be sure you are opening a file successfully.

Modern Java offers the Path, File, and Files classes to make handling files on storage much easier.

Example:

package work.basil.example;

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Csver
{
    public static void main ( String[] args )
    {
        Csver app = new Csver() ;
        app.writeDummyFile() ;
    }

    private void writeDummyFile ()
    {
        Path path = Paths.get( "/Users/basilbourque/dummy.txt" ) ;
        // Use try-with-resources to auto-close the file if successfully opened.
        try ( 
            BufferedWriter writer = Files.newBufferedWriter( path ) ;  // Will be automatically closed if successfully opened.
        )
        {
            writer.write( "Bonjour le monde!" ) ;
        } catch ( IOException e )
        {
            e.printStackTrace() ;
        }
    }

}

Use a library for CSV

Next, for CSV or Tab-delimited files or such, use a library. I use Apache Commons CSV. Search Stack Overflow for many examples of using this and other such libraries to read and write these kinds of files.

Use CSVFormat to define the type of file. Here we use standard CSV as defined by RFC 4180. Note that standard CSV uses CRLF (CARRIAGE RETURN LINE FEED) to denote line breaks rather then LF (LINE FEED) seen commonly in Unix-like platforms.

When opening the file, we specify UTF-8 character encoding. UTF-8 is generally the best encoding to use; it covers all the Unicode characters, and is a superset of US-ASCII.

The CSVPrinter::print method adds a field at a time when outputting a row. We terminate the row by calling CSVPrinter::println.

I renamed your i & j variables to be meaningful.

I added column names at the top of the file. You may want to keep or discard that feature, up to you.

Notice how we are using try-with-resources syntax to auto-close our file.

package work.basil.example;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.CSVRecord;

import javax.swing.*;
import javax.swing.table.TableModel;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Csver
{
    public static void main ( String[] args )
    {
        Csver app = new Csver();

        // Practice writing a simple file.
        app.writeDummyFile();

        // Write out the data in a JTable to standard CSV file.
        JTable jtable = app.newJTable();
        app.writeCSV( jtable.getModel() );

        System.out.println( "« fin »" );
    }

    private void writeCSV ( final TableModel model )
    {
        CSVFormat format = CSVFormat.RFC4180;
        Path path = Paths.get( "/Users/basilbourque/animals.csv" );
        try (
                BufferedWriter writer = Files.newBufferedWriter( path , StandardCharsets.UTF_8 ) ;
                CSVPrinter printer = new CSVPrinter( writer , format ) ;
        )
        {
            // Print column headers, if you want.
            for ( int columnIndex = 0 ; columnIndex < model.getColumnCount() ; columnIndex++ )
            {
                printer.print( model.getColumnName( columnIndex ) );
            }
            printer.println();

            // Print rows.
            for ( int rowIndex = 0 ; rowIndex < model.getRowCount() ; rowIndex++ )
            {
                for ( int columnIndex = 0 ; columnIndex < model.getColumnCount() ; columnIndex++ )
                {
                    printer.print( model.getValueAt( rowIndex , columnIndex ) );
                }
                printer.println();
            }
        } catch ( IOException e )
        {
            e.printStackTrace();
        }
    }

    private JTable newJTable ()
    {
        String[] columnNames = { "Species" , "Name" };
        Object[][] data = {
                { "Dog" , "Delilah" } ,
                { "Cat" , "René" } ,
                { "Bird" , "Jordan" }
        };
        JTable table = new JTable( data , columnNames );
        return table;
    }

    private void writeDummyFile ()
    {
        Path path = Paths.get( "/Users/basilbourque/dummy.txt" );
        // Use try-with-resources to auto-close the file if successfully opened.
        try ( BufferedWriter writer = Files.newBufferedWriter( path ) )
        {
            writer.write( "Bonjour le monde!" );
        } catch ( IOException e )
        {
            e.printStackTrace();
        }
    }

}

这篇关于使用Java导出到.csv不会输出文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆