将随机数插入文件并读取这些随机数

时间:2015-07-31 11:34:52

标签: java

我想在文件中插入随机数并读取这些randoms数字并存储到java中的数组中。

请查看以下代码

import java.io.*;
import java.util.*;

public class sort implements Serializable
{
    public static void main(String args[]) throws Exception
    {
        int[] al;
        Random rand=new Random();
        Scanner sc=new Scanner(System.in);
        File fi=new File("sort.txt");
        fi.createNewFile();
        FileOutputStream fs=new FileOutputStream(fi);
        ObjectOutputStream os=new ObjectOutputStream(fs);
        System.out.println("enter how many numbers you need to sort");
        int n=sc.nextInt();

        al=new int[n];

        for(int k=0;k<al.length;k++)
            os.write(rand.nextInt(10));

        FileInputStream fs1=new FileInputStream("./sort.txt");
        ObjectInputStream ois=new ObjectInputStream(fs1);

        ois.read();
        /* i need to use this file and retrieve the randoms numbers
         * from the file and store those numbers from the file and need to sort */
    }
}

2 个答案:

答案 0 :(得分:0)

如果你想保留你的代码......你可以读取这样的值:

<强>写:

...
for (int k = 0; k < al.length; k++) {
    os.writeInt(rand.nextInt());
}
os.close();
...

<强>读:

FileInputStream fs1 = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fs1);

int[] in = new int[n];
for (int k = 0; k < al.length; k++) {
    in[k] = ois.readInt();
    //System.out.println(in[k]);
}

答案 1 :(得分:0)

你可能需要这个:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.Serializable;
import java.util.Random;
import java.util.Scanner;

public class Sort implements Serializable {

    private static final long serialVersionUID = 1L;
    private static final File file = new File("sort.txt");

    public static void main(String args[]) throws Exception {
        Random rand = new Random();
        Scanner sc = new Scanner(System.in);
        String sCurrentLine;
        String[] array = null;

        if (!file.exists()) {
            file.createNewFile();
        }
        System.out.println("enter how many numbers you need to sort");
        int n = sc.nextInt();
        int[] al = new int[n];
        try (FileWriter fw = new FileWriter(file);) {
            for (int k = 0; k < al.length; k++) {
                fw.write(new Integer(rand.nextInt(10)).toString());
            }
        }
        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            while ((sCurrentLine = br.readLine()) != null) {
                array = sCurrentLine.toString().split("");
            }
            for (int counter = 0; counter < array.length; counter++) {
                System.out.println(array[counter]);
            }
        }
        sc.close();
    }
}