Reading specific part of a file
Im trying to design a java program that reads a txt file such as the one below:
0 400 450 510 670 493 958
1 500 560 630 5633
2 625 676 740
3 1000 1250 1600
5 2435 235 2654
Then through a user prompt, outputs a specific number from a specific line to the user, i.e.
Would print 450
i have little knowledge of java, and im not sure if i need to read the whole file into arrays or i can get java just to read a specific line and column from it
i have tried using arrays but as the txt file can be of any size it got confusing!
Thanks to you all
erm, you cant consider files as columns and rows, because thye are just a stream of data. your file is hence looking like:
0 400 450 510 670 493 958CRLF1 500 560 630 5633CRLF2 625 676 740CRLF3 1000 1250 1600CRLF4 432CRLF5 2435 235 2654
and hence it is impossible to calculate where to go for row 4 col 1 etc
you shoudl read the whole thing into an array of arrays. the basic logic goes like this:
define an array called theFile (yes, two sets of )
define an ArrayList object
define a BufferedReader, wrapped around a FileReader, pointing to your file
repeatedly bufferedreader.readLine() a string in, and add it to the arrayList
at the end of the file, ask the arraylist how big it is.
make theFile = new String[howBigItIs] (yes, leave the second one blank
step through the arraylist, pulling each string out.
split() the string based on space, and you will get a String array out of the split operation
assign the String to theFile[incrementingIndex]
now you have your whole file represented as:
be sure to check the bounds before attempting to access the array
if(theLineNumber < theFile.length && theColumn < theFile[theLineNumber].length)
if theLineNumber is out of range, then the second part of the test wont run (first is false, and theres no way a FALSE AND <anything> can be true)
note: arrayList are like arrays but they grow automatically.. hence you can have them grow,grow,grow.. and then ask them for their size and make a fixed size array based on that
for examples of BufferedReader and readLine, search for posts by me that cotain these words
Top DevX Stories
Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL