Java Use Data from External Text File
I have a text file containing the first 1000 prime numbers and I have written a method to read the data from said text file.
I would like to know how to use the data from this file and apply it to another method.
Something along the lines o开发者_JS百科f:
read data from file;
use first eight numbers and apply to this method;
Any help would be appreciated.
Read the file and store each number into an array or list. You can then get the numbers you need by using the index of the array.
Reading from file is simple, assuming you have one line per number -
BufferedReader br = new BufferedReader(new FileReader("<your-text-file>"));
String txtNum;
while((txtNum = br.readLine()) != null)
{
//txtNum is the number read, use it however you need
if (txtNum.length() > 8) {
thisMethod(txtNum.substring(0, 8));
}
}
Use Scanner
to read the data from the file and store each line in an array (or ArrayList
) of int
s. The get a subset of that array and pass it to a method supporting variable-length arguments (for example). Something like :
public static void main(String[] args) {
ArrayList<Integer> primes = new ArrayList<Integer>();
readPrimeData(new File("path/to/data"), primes);
someMethod(primes.subList(0, 8).toArray(new Integer[0]));
}
static public boolean readPrimeData(File dataFile, ArrayList<Integer> data) {
boolean err = false;
try {
Scanner scanner = new Scanner(dataFile);
String line;
while (scanner.hasNext()) {
line = scanner.nextLine();
try {
data.add(Integer.parseInt(line));
} catch (NumberFormatException e) {
e.printStackTrace();
err = true;
}
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
err = true;
}
return err;
}
static public void someMethod(Integer...primes) {
// primes is Integer[]
}
The method someMethod
can also be called like
someMethod(1, 2, 3, 5, 7);
First, you have to know how you information is organized. For instance, you could have your 1000 first prime nunbers organized this way:
1
2
3
5
7...
Or this way:
1-2-3-5-7-11...
You can use the StringBuilder (or just a String) to keep the numbers of your file (assuming that your text is like the second way above). As the numbers are separated by a dash you could use a substring that can take the first 8 numbers to some method.
BufferedReader br = new BufferedReader(new FileReader("Prime Nunbers.txt"));
String num;
int count = 1;
while((num= br.readLine()) != null) {
if( count <= 8 )
someMethod( num.subString(0, num.indexOf("-")) );
}
But if you have your numbers organized like the 1st way (one number per line) you could do something like this:
BufferedReader br = new BufferedReader(new FileReader("Prime Nunbers.txt"));
String num;
int count = 1;
while((num = br.readLine()) != null) {
if( count <= 8 )
someMethod( num );
num = "";
}
If you want to use these first 8 numbers at once you can just read the file entirely and then use some substring depending the way these numbers are read.
精彩评论