-1

I'm trying to write a program for homework that opens a file that is given by the string and reads a series of comma separated integer values into an array, which it then returns.

import java.util.Arrays;

...

int[] readVector(String filename) throws IOException {
    File f = new File(filename);

    FileOutputStream fos = new FileOutputStream(f, true);

    PrintWriter pw = new PrintWriter(fos);
    pw.println("");
    pw.close();

    FileReader fr = new FileReader(f);
    BufferedReader bfr = new BufferedReader(fr);
    while (true) {
        String s = bfr.readLine();
        if (s == null) {
            break;
        }
        System.out.println(s);
    }
    bfr.close();;

    return NOIDEA;
}

Consider this...

Matrix m = new Matrix();
System.out.println(Arrays.toString(m.readVector("vector.txt"))); // print "[1, 2, 3, 4]"

2 Answers2

0

Read the file contents to an array, then convert using this:

Vector<Integer> returnVec = new Vector(Arrays.asList(YOUR_ARRAY));

If you're having trouble also reading the text file into an array then look at this question.

Community
  • 1
  • 1
bpgeck
  • 1,592
  • 1
  • 14
  • 32
  • My only problem with this is that the return statement needs to be an int array. – asdfjklasf Oct 30 '15 at 21:01
  • Perfect. In that case just return the original array. So here's the flow to give you an idea: FIrst, read all ints from file into an array. If that's all you need to do then check the link in my answer. If you then need to convert it to a vector, use the syntax I provided. When you are finished with any operation, just return the original integer array. – bpgeck Oct 30 '15 at 21:04
0

Based on your description, your implementation contains a lot of stuff it doesn't really need, for example FileOutputStream and PrintWriter. And if the values are on a single line, then it's enough to process a single line, which is easy enough to do with a Scanner.

This should do it:

int[] readVector(String filename) throws IOException {
    return Arrays.stream(new Scanner(new File(filename)).nextLine().split(","))
           .mapToInt(Integer::parseInt).toArray();
}
janos
  • 120,954
  • 29
  • 226
  • 236