Advertisement
MrPolywhirl

ReadFile

Feb 16th, 2014
182
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.29 KB | None | 0 0
  1. All you need to do is loop over every line in the file and store the values as integers.
  2.  
  3. Easiest way to populate an array of integers from a file:
  4.  
  5. <!-- language: lang-java -->
  6.  
  7. import java.io.*;
  8. import java.util.*;
  9.  
  10. public class ReadFile {
  11. public static void main(String[] args){
  12. BufferedReader br = null;
  13. Integer[] array = null;
  14. String filename = "input.txt";
  15.  
  16. try {
  17. List<Integer> list = new ArrayList();
  18. String line = "";
  19. br = new BufferedReader(new FileReader(filename));
  20.  
  21. while ((line = br.readLine()) != null)
  22. list.add(Integer.parseInt(line));
  23.  
  24. array = list.toArray(new Integer[list.size()]);
  25. } catch (Exception e) {
  26. e.printStackTrace();
  27. } finally {
  28. try {
  29. if (br != null)
  30. br.close();
  31. } catch (IOException e) {
  32. e.printStackTrace();
  33. }
  34. }
  35.  
  36. if (array != null) {
  37. for (Integer i : array)
  38. System.out.printf("%d", i);
  39. }
  40. }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement