0

如果这是一个愚蠢的问题,我很抱歉,但我已经考虑了超过 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”时会发生什么?我是保存 10 个对象,每个对象包含 1 个元素,还是保存 1 个对象,每个对象包含 10 个元素?每当我按“agreg”时,它会覆盖我的对象还是会保存新的对象?

或者我怎么能保存 10 个元素的 1 个对象。

稍后我会将这些对象用于 JList,并将每个对象读入另一个文件以将它们的元素“打印”到 JLabel 中......

4

3 回答 3

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;
}

把它放在你的主要方法中,你可能需要遍历数组以获取数组中的所有元素

    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]);
        }
    }

希望这会有所帮助

于 2013-07-09T00:55:46.143 回答
0

你的kanji类应该实现Serializable接口。在实现中,您定义如何kanji将其内容编码为流以及如何kanji从流中解码内容。

于 2013-07-08T22:58:33.343 回答
0

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

于 2013-07-08T23:42:59.170 回答