Hola a todos, lo que quiero hacer es un programa que me lea los números que hay dentro de un documento txt y los guarde dentro de un array, cabe decir que la dirección del documento la debe introducir el usuario.
Les adjunto mi código
import java.util.Scanner;
public class ReadFile{
public static void main(String[] args) {
// Initialize the variables
String fileDirection;
// Creating Objects
Scanner keyboard = new Scanner(System.in);
Numbers newArch = new Numbers();
// Asking for the direction of the file
System.out.println("\n\n*--- Give me the location of your text document ---*");
System.out.println("Here's an example of what do you need to put: C:\\Users\\Example\\Documents\\File.txt");
fileDirection = keyboard.nextLine();
// Sending the direction of the file
newArch.readTxt(fileDirection);
// Here we print the numbers of the document
System.out.println("\nThese are the numbers of your document :) \n\n");
newArch.printArray();
}
}
import java.util.Scanner;
import java.util.Arrays;
import java.io.File;
public class Numbers{
// Creating an empty array
int docNumbers[];
public void readTxt(String direction){
// We create a temporal variable to save the numbers
int num = 0, count = 0;
Scanner myArch = null;
try{
myArch = new Scanner(new File(direction));
}catch(Exception e){
System.out.println("Document not found");
}
// This loop ends until readBuffer runs out of data (numbers)
while(myArch.hasNext()){
num = myArch.nextInt();
docNumbers[count] = num;
count++;
}
}
// This method is to display the numbers of the array
public void printArray(){
System.out.println(Arrays.toString(docNumbers));
}
public Numbers(){
}
}