Skip to content

Instantly share code, notes, and snippets.

@hadizz
Last active April 22, 2020 19:23
Show Gist options
  • Save hadizz/bb5efa4c8a58e46718c9eb9def3faa6d to your computer and use it in GitHub Desktop.
Save hadizz/bb5efa4c8a58e46718c9eb9def3faa6d to your computer and use it in GitHub Desktop.
Read from file with java
/**
* @author Hadi Zare
*
*/
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class readFromFile {
public static void main(String[] args) throws FileNotFoundException {
// we assume that text file has these lines
// 1 2 3 4 5 6 7
// 2 3 4 5 6 7
// 3 4 5 6 7
final String PATH = "text.txt";
File file = new File(PATH);
Scanner scanner = new Scanner(file);
String[] stringArray;
int[] integerArray;
while (scanner.hasNextLine()) {
stringArray = scanner.nextLine().split(" ");
integerArray = Arrays.stream(stringArray).mapToInt(Integer::parseInt).toArray();
// do whatever you want with integer integerArray
}
scanner.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment