简体   繁体   中英

Java read integer arrays from multiple files

I'm relatively new to Java, so I have to look up how to do things constantly. I'm working on a project that involves analyzing a number of familiar sorts such as heap sort, merge sort, etc. I wrote a bit of code to produce a variety of different arrays, each in their own .txt file. Here is a portion of the code:

import java.io.*;
import java.util.Arrays;
import java.util.Collections;

public class ArrayBuilder {

public static void main(String[] args) throws IOException { 
    for(int i = 2; i < 7; i++) {
        int aLength = (int)Math.pow(10, i);
        buildAscendingArray(aLength);
        buildDescendingArray(aLength);
        buildRandomArray(aLength);
    }
}
public static void buildAscendingArray(int arrayLength) throws IOException {
    File file = new File("arrays_" + arrayLength + "A.txt");
    PrintWriter printWriter = new PrintWriter(file);
    int[] array = new int[arrayLength];
    for(int i = 0; i < array.length; i++) {
        array[i] = i + 1;
    }
    printWriter.println(Arrays.toString(array));
    printWriter.close();
}

I didn't include the random and descending methods as they are more or less the same so trying to save room. So...

I already have all the sorts coded, I'm just trying to figure out how to read in the integer arrays so I can run them through the different sorts. I'm also trying to factor adding in System.nanoTime() to clock the time it takes to run each sort so I can compare them given the various inputs. Not sure if this needs to be added into the method for each sort or whether it can be implemented in the call ie. System.nanoTime(heapsort(array))) ?

Ultimately I'm looking for some help on getting the .txt files into a usable array in order to pass it through each sort. I output all to text files in the first place to make sure the exact same array is run through each sort.

I'm somewhat familiar with Scanner, but have also read about FileRead and/or BufferedReader and possibly some other approaches. I'm just not experienced enough to know what would work best in this situation and the best way to implement it. Help would be much appreciated.

If you just need to save arrays to file storage and construct them back you can use serialization.

This class is just to give you an idea of how it would work.

public class ArrayReaderWriter {

    public static void main(String[] args) throws Exception {
        writeArray(20);
        readArray(20);
    }

    public static void writeArray(int arrayLength) throws IOException {
        File file = new File("arrays_" + arrayLength + "A.ser");
        ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(file));
        int[] array = new int[arrayLength];
        for (int i = 0; i < array.length; i++) {
            array[i] = i + 1;
        }
        os.writeObject(array);
    }

    public static void readArray(int arrayLength) throws IOException, ClassNotFoundException {
        File file = new File("arrays_" + arrayLength + "A.ser");
        ObjectInputStream is = new ObjectInputStream(new FileInputStream(file));
        int[] array = (int[]) is.readObject();
        // Printing here to verify 
        for (int i = 0; i < array.length; i++) {
            System.out.println(array[i]);
        }
    }

}

Note : I can understand saving the random array if you want to run the different sorts with the same array in different executions. But the ascending and descending arrays can always be constructed on every execution.

Regarding System.nanoTime()

See https://docs.oracle.com/javase/8/docs/api/java/lang/System.html#nanoTime-- for a detailed explanation.

EDIT

If you have already generated the text files use @Antoniossss solution. You will only need to modify the delimiter as I mentioned in my comment since you are reading existing files.

Test

Scanner scanner = new Scanner("[1, 2, 3]");
scanner.useDelimiter("(\\s)*[\\[,\\]](\\s)*");
while(scanner.hasNextInt()) {
    System.out.println(scanner.nextInt());
}

Output

1
2
3

Use some delimetered file format for such purposes and read it using scanner. Lets say our delimeter is character is ; . Store your array like this

File file = new File("arrays_" + arrayLength + "A.txt");
PrintWriter printWriter = new PrintWriter(new BufferedWriter(new FileWriter(file)));
printWriter.print(1);
for(int i = 1; i < array.length; i++) {
   printWriter.print(';'); // delimeter
   printWriter.print(i+1);
}
printWriter.close();

To read it back, use Scanner in simillar way to the following code;

ArrayList<Integer> arr=new ArrayList<>();
Scanner scan=new Scanener(new File("yourfile));
scan.useDelimeter(';');
while(scan.hasNextInt()){
    arr.add(scan.nextInt());
}

Should work just fine. You can always use a newline as a delimeter as well.

EDIT : If you dont need to have array storred in human readable form, you can use serialization just like @Shire Resident explained in his answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM