问题如题:不知道java中怎么把数组写入到一个文件中然后读到一个数组中?
数组内容是float类型。

解决方案 »

  1.   

    简单些就把float转成String,用分隔符保存到文件,然后读取专业些就用bytebuffer,转成byte用16进制保存到文件
    用序列化readObject和writeObject也可以
      

  2.   

    如果只是为了复制数组. 为何不直接copy?
      

  3.   


    import java.io.*;
    public class test{
    public static void main(String [] args){
    String [] ss={"sss","ss3","ss4"};
    String [] tem;
    try{
    ObjectOutputStream   oos=new ObjectOutputStream(new FileOutputStream("www.txt")); 
    oos.writeObject(ss);
    ObjectInputStream    ois=new ObjectInputStream(new FileInputStream("www.txt"));
    tem=(String[])ois.readObject();
    for(int i=0;i<tem.length;i++){
    System.out.println(tem[i]);
    }
    }
    catch(FileNotFoundException e){

    }
    catch(ClassNotFoundException e){

    }
    catch(IOException e){

    }
    }
    }
      

  4.   


    我写了一个专门操作float类型的读写,用到的是DataInputStream和DataOutputStream字节流。public class ArraysDemo { float[] read() {
    try {
    DataInputStream dataIn = new DataInputStream(new FileInputStream(
    "demo.txt"));
    float[] ff = new float[3];  // 此处这个3是固定的,你想办法把它变活!
                                                                // (提示:先读一遍所有,再把数字把数字得到)
    float f = 0.0F;
    int i = 0;
    do {
    try {
    f = dataIn.readFloat();
    } catch (Exception ex) {
    break;
    }
    ff[i] = f;
    i++;
    } while (dataIn.available() != 0);
    dataIn.close(); return ff;
    } catch (FileNotFoundException ex) {
    System.out.println(ex.getMessage());
    } catch (IOException ex) {
    System.out.println(ex.getMessage());
    }
    return null;
    } void write(float[] ff) {
    try {
    DataOutputStream dataOut = new DataOutputStream(
    new FileOutputStream("demo.txt"));
    for (int i = 0; i < ff.length; i++) {
    dataOut.writeFloat(ff[i]);
    }
    dataOut.flush();
    dataOut.close();
    } catch (IOException ex) {
    System.err.println(ex.getMessage());
    }
    }

    public static void main(String[] args) {
    ArraysDemo o = new ArraysDemo();
    // 写
    float[] ff = {1.1F, 1.2F, 1.3F};
    o.write(ff);
    // 读
    ff = o.read();
    for (int i = 0; i < ff.length; i++) {
    System.out.println(ff[i]);
    }
    }
    }
      

  5.   


    // 你把do...while循环条件dataIn.available() != 0改为true吧,那个条件没用。
    http://topic.csdn.net/u/20081130/15/2ee11370-774f-4e7f-9700-d22116b2e2dd.html