Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Reading a file into an array

Tags:

java

arrays

I have a file (called "number.txt") which I want to read to an array in Java. How exactly do I go ahead and do this? It is a straight-forward "1-dimensional" file, containing 100 numbers.

The problem is that I get an exception every time. Apparently it can't find it (I am sure its spelled correctly). When looking through code examples, it doesn't specify the file's entire file path, only the name of the file itself. How would I go about doing that if its necessary?

Also, when reading the file, will the array automatically contain all the lines of the file, or will I have to make a loop which which copies every line to corresponding subscript i?

I've heard of BufferedReader class, what it's purpose, and how does it corelate to reading input?

like image 385
Northener Avatar asked Nov 12 '08 22:11

Northener


2 Answers

Here is some example code to help you get started:

package com.acme;  import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List;  public class FileArrayProvider {      public String[] readLines(String filename) throws IOException {         FileReader fileReader = new FileReader(filename);         BufferedReader bufferedReader = new BufferedReader(fileReader);         List<String> lines = new ArrayList<String>();         String line = null;         while ((line = bufferedReader.readLine()) != null) {             lines.add(line);         }         bufferedReader.close();         return lines.toArray(new String[lines.size()]);     } } 

And an example unit test:

package com.acme;  import java.io.IOException;  import org.junit.Test;  public class FileArrayProviderTest {      @Test     public void testFileArrayProvider() throws IOException {         FileArrayProvider fap = new FileArrayProvider();         String[] lines = fap                 .readLines("src/main/java/com/acme/FileArrayProvider.java");         for (String line : lines) {             System.out.println(line);         }     } } 

Hope this helps.

like image 132
toolkit Avatar answered Sep 20 '22 19:09

toolkit


import java.io.File;  import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path;  import java.util.List;  // ...  Path filePath = new File("fileName").toPath(); Charset charset = Charset.defaultCharset();         List<String> stringList = Files.readAllLines(filePath, charset); String[] stringArray = stringList.toArray(new String[]{}); 
like image 45
Hélio Santos Avatar answered Sep 21 '22 19:09

Hélio Santos