是否可以将数组的ArrayList添加到文件中?

时间:2013-07-08 22:39:53

标签: java file object arraylist jtable

我很抱歉,如果这是一个愚蠢的问题,但我已经考虑了超过5天,阅读文档和谷歌搜索,但我没有找到答案,以及如何使用它一个代码(我的意思是例子),太多等等,让我们回答问题:

我的问题是,正如标题所示:是否可以将数组的ArrayList添加到文件中?

如果是的话,我有这些代码(SSCCE):

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.*;
import java.awt.Color;
import java.awt.GridLayout;
import java.util.*;
class create_study_list{
public static JFrame his;
public static JRadioButton ka, si, on, kun;
public static ButtonGroup tipo;
public static JPanel botones, botarr, botaba, tipos;
public static JButton agreg, canc, selec, deselec;
public static JTable table;
public static TableColumn column;
public static DefaultTableModel model;
public static JScrollPane scroll;
public static DefaultTableCellRenderer r, r2;
public static kanji k;
public static ArrayList<kanji> lista_estudio=new ArrayList<kanji>();
public static void agregar(){
    kanji aux = new kanji();
    String nombre = "nombre";
    for(int j=0; j<10; j++){
        aux.set_unicode((String)table.getValueAt(j,1), j);
        aux.set_significado((String)table.getValueAt(j,2), j);
        aux.set_onyomi((String)table.getValueAt(j,3), j);
        aux.set_kunyomi((String)table.getValueAt(j,4), j);
        aux.set_agregar((boolean)table.getValueAt(j,5), j);
        aux.set_tipo(1);
    }
    lista_estudio.add(aux);
    try{
        ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream("study_list_kanji.txt"));
        out.writeObject(lista_estudio);
        out.close();
    }
    catch(Exception exp){
    }
}
public static void main(String args[]){

    ka = new JRadioButton("Kanji");
    si = new JRadioButton("Significado");
    on = new JRadioButton("Onyomi");
    kun = new JRadioButton("Kunyomi");
    tipo = new ButtonGroup();

    k = new kanji();
    his = new JFrame("Creacion de Listas de Estudio");
    agreg = new JButton("Agregar seleccionados");
    canc = new JButton("Cancelar");
    selec = new JButton("Seleccionar todos");
    deselec = new JButton("No seleccionar nada");
    table = new JTable();
    column = null;
    model = new DefaultTableModel(k.get_data(), k.get_header());
    tipos = new JPanel(new FlowLayout(FlowLayout.CENTER));
    botones = new JPanel(new BorderLayout());
    botarr = new JPanel(new FlowLayout(FlowLayout.TRAILING));
    botaba = new JPanel(new FlowLayout(FlowLayout.CENTER));
    tipo.add(ka);
    tipo.add(si);
    tipo.add(on);
    tipo.add(kun);
    tipos.add(ka);
    tipos.add(si);
    tipos.add(on);
    tipos.add(kun);
    botarr.add(deselec);
    botarr.add(selec);
    botaba.add(canc);
    botaba.add(agreg);
    botones.add(tipos, BorderLayout.NORTH);
    botones.add(botarr, BorderLayout.CENTER);
    botones.add(botaba, BorderLayout.SOUTH);
    agreg.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            agregar();
        }
    });
    r = new DefaultTableCellRenderer() {
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            setForeground(Color.blue);
            setHorizontalAlignment(JLabel.CENTER);
            setFont(new Font("Microsoft JhengHei", Font.BOLD, 50));
            return this;
        }
    };
    r2 = new DefaultTableCellRenderer() {
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            setHorizontalAlignment(JLabel.CENTER);
            setFont(new Font("Microsoft JhengHei", Font.BOLD, 13));
            return this;
        }
    };
    table.setFont(new Font("Microsoft JhengHei", Font.BOLD, 13));       
    table = new JTable(model){
        @Override
        public boolean isCellEditable(int row, int col){
            switch(col){
                case 0:
                    return false;
                case 1:
                    return false;
                case 2:
                    return false;
                case 3:
                    return false;
                case 4:
                    return false;
                case 5:
                    return true;
                default:
                    return false;
            }
        }
        @Override
        public Class getColumnClass(int column) {
            switch (column) {
                case 0:
                    return String.class;
                case 1:
                    return String.class;
                case 2:
                    return String.class;
                case 3:
                    return String.class;
                case 4:
                    return String.class;
                case 5:
                    return Boolean.class;
                default:
                    return Boolean.class;
            }
        }
    };

    table.getColumnModel().getColumn(0).setCellRenderer(r2);
    table.getColumnModel().getColumn(1).setCellRenderer(r);
    table.getColumnModel().getColumn(2).setCellRenderer(r2);
    table.getColumnModel().getColumn(3).setCellRenderer(r2);
    table.getColumnModel().getColumn(4).setCellRenderer(r2);

    for (int i = 0; i < 6; i++) {
        column = table.getColumnModel().getColumn(i);
        switch(i){
            case 0:
                column.setMinWidth(35);
                column.setMaxWidth(35);
                break;
            case 1:
                column.setMinWidth(60);
                column.setMaxWidth(60);
                break;
            case 2:
                column.setMinWidth(100);
                column.setPreferredWidth(400);
                break;
            case 3:
                column.setMinWidth(125);
                column.setPreferredWidth(395);
                break;
            case 4:
                column.setMinWidth(250);
                column.setPreferredWidth(400);
                break;
            case 5:
                column.setMinWidth(50);
                column.setMaxWidth(50);
                break;
            default:
                column.setPreferredWidth(875);
                break;
        }
    }
    table.setRowHeight(table.getRowHeight()+70);
    table.setModel(model);
    table.getTableHeader().setReorderingAllowed(false);

    his.add(table, BorderLayout.CENTER);
    his.add(botones, BorderLayout.SOUTH);
    his.add(table.getTableHeader(), BorderLayout.NORTH);
    scroll = new JScrollPane(table);
    his.add(scroll);
    his.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    his.setTitle("Lista de Kanji");
    his.setSize(1350, 700);
    his.setResizable(false);
    his.setVisible(true);
    his.setLocationRelativeTo(null);

}
}

我还有其他代码,在上面的代码中需要:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
class kanji{
String unicode[];
String significado[];
String onyomi[];
String kunyomi[];
boolean agregar[];
int i, tipo;

kanji(){
    unicode = new String[200];
    significado = new String[200];
    onyomi = new String[200];
    kunyomi = new String[200];
    agregar = new boolean[200];
    i = 0;
    tipo = 0;
}
int get_tipo(){
    return tipo;
}
void set_tipo(int t){
    this.tipo = t;
}
String []get_unicode(){
    unicode = new String[]{
        "\u4e00",
        "\u4e8c",
        "\u4e09",
        "\u56db",
        "\u4e94",
        "\u516d",
        "\u4e03",
        "\u516b",
        "\u4e5d",
        "\u5341"
    };
    return unicode;
}
String []get_significado(){
    significado = new String[]{
        "Uno, 1",
        "Dos, 2",
        "Tres, 3",
        "Cuatro, 4",
        "Cinco, 5",
        "Seis, 6",
        "Siete, 7",
        "Ocho, 8",
        "Nueve, 9",
        "Diez, 10",
    };
    return significado;
}
String []get_onyomi(){
    onyomi = new String[]{
        "ICHI, ITSU",
        "NI, JI",
        "SAN, JOU",
        "SHI",
        "GO",
        "ROKU, RIKU",
        "SHICHI",
        "HACHI",
        "KYUU, KU",
        "JUU, JITTSU, JUTTSU",
    };
    return onyomi;
}
String []get_kunyomi(){
    kunyomi = new String[]{
        "hito, hito(tsu)",
        "futa, futa(tsu), futata(bi)",
        "mi, mi(tsu), mitt(tsu)",
        "yo, yo(tsu), yot(tsu), yon",
        "itsu, itsu(tsu)",
        "mu, mu(tsu), mut(tsu), mui",
        "nana, nana(tsu), nano",
        "ya, ya(tsu), yat(tsu), you",
        "kokono, kokono(tsu)",
        "too, to",
    };
    return kunyomi;
}
boolean []get_agregar(){
    agregar = new boolean[]{
        true,
        true,
        true,
        true,
        true,
        true,
        true,
        true,
        true,
        true,
    };
    return agregar;
}
void set_agregar(boolean agre, int p){
    this.i = p;
    this.agregar[i] = agre;
}
void set_unicode(String uni, int q){
    this.i = q;
    this.unicode[i] = uni;
}
void set_significado(String sig, int r){
    this.i = r;
    this.significado[i] = sig;
}
void set_onyomi(String ony, int s){
    this.i = s;
    this.onyomi[s] = ony;
}
void set_kunyomi(String kuny, int t){
    this.i = t;
    this.kunyomi[i] = kuny;
}
Object [][]get_data(){
    Object data[][] = new Object[10][6];
    String uni[] = new String [10];
    String sig[] = new String [10];
    String on[] = new String [10];
    String kun[] = new String [10];
    boolean agre[] = new boolean [10];
    uni = get_unicode();
    sig = get_significado();
    on = get_onyomi();
    kun = get_kunyomi();
    agre = get_agregar();
    for(int k=0; k<10; k++){
        data[k][0] = k+1;
        data[k][1] = uni[k];
        data[k][2] = sig[k];
        data[k][3] = on[k];
        data[k][4] = kun[k];
        data[k][5] = agre[k];
    }
    return data;
}
String []get_header(){
    String header2 [] = new String[]{"#", "KANJI", "SIGNIFICADO", "LECTURA ON", "LECTURA KUN", "Agregar"};
    return header2;
}
}

当我保存文件“study_list_kanji.txt”时会发生什么?我是保存每个1个元素的10个对象还是保存1个10个元素的对象?每当我按下'agreg'时它会覆盖我的对象还是会保存新对象?

或者如何保存10个元素的1个对象。

我稍后会将这些对象用到JList中,然后我会将每个对象读入另一个文件,将其元素“打印”到JLabel中......

3 个答案:

答案 0 :(得分:1)

您正在将10个元素的一个对象写入该文件。因此,当您阅读时,您将返回一个Arraylist对象。如前面的答案所述,你必须实施 Kanji实现了Serializable来保存。 阅读你可以这样做。

    private static ArrayList<Kanji> readFile() {
    ArrayList<Kanji> kanjis = null;
    try {
        ObjectInputStream in = new ObjectInputStream(new FileInputStream(
                "study_list_kanji.txt"));
        while (true) {
            try {
                try {
                    kanjis = ((ArrayList<Kanji>) in.readObject());
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            } catch (EOFException e) {
                return kanjis;
            }
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return kanjis;
}
  

把它放在你的main方法中,你可能需要迭代数组来获取数组中的所有元素

    ArrayList<Kanji> kanjis = readFile();
    if (kanjis != null) {
        for (Kanji kanji : kanjis) {
            System.out.println("kunyomi:  " + kanji.get_kunyomi()[0]);
            System.out.println("onyomi:  " + kanji.get_onyomi()[0]);
            System.out.println("significado:  "
                    + kanji.get_significado()[0]);
            System.out.println("unicode:  " + kanji.get_unicode()[0]);
        }
    }
  

希望这会有所帮助

答案 1 :(得分:0)

您的kanji课程应该实现Serializable界面。在实现中,您可以定义kanji将其内容编码为流的方式以及kanji如何解码流中的内容。

答案 2 :(得分:0)

可以使用Java的序列化工具来执行此操作,但它不会生成可读文件。如果不是这种情况,请查看本教程http://www.tutorialspoint.com/java/java_serialization.htm,其中包含序列化和反序列化的示例。但是,如果您希望获得可读的内容,那么可以考虑将数组的元素写成用逗号分隔的行,并且每个新行都是arraylist中的条目。希望它有所帮助。