Results 1 to 6 of 6
Thread: Accessing Data from a .txt file
- 01-29-2008, 12:10 AM #1
Member
- Join Date
- Jan 2008
- Posts
- 3
- Rep Power
- 0
Accessing Data from a .txt file
Hi guys,
I hope you are able to help me :D
I'm very new to Java, and have so far just spent a lot of hours playing around and using google when i get stuck with something.
Anyway, in a little program I'm currently doing I'd like to set an int variable to a value that is stored in a .txt file.
For example, in pseudo code it would work something like this:
The main purpose of doing this is so that every time the program is run, int a takes its value from the text file. Whilst running the program I might like to change the value of a, in which case the txt file will need changing so that the changes are reflected upon the next run of the programm. Essentially its like using a GET SQL command with a MySQL database, but far simpler!!! (Hopefully :p)Java Code:int a; a = the value of the int stored in this text file(hello.txt);
Any help with this would be greatly appreciated!
- 01-29-2008, 07:09 AM #2
You can use the FileReader class for this.
See basically, Scanner has a constructor for a FileReader, so we can pass the FileReader object to the scanner, thus giving us the ability to use the Scanner methods on it. In this case, we will use the nextInt() method to obtain the int value in the .txt file.Java Code:FileReader reader = new FileReader("hello.txt"); Scanner console = new Scanner(reader); //Use a scanner to read the info int x = console.nextInt();
If you have any more questions, let me know, i enjoy file reading and writing.
- 01-30-2008, 12:42 AM #3
Member
- Join Date
- Jan 2008
- Posts
- 3
- Rep Power
- 0
Thanks, that worked like a charm!!!
Just one question though - how can i edit the contents of the text file from within the programm e.g. change the value of the int x.
- 01-30-2008, 01:23 AM #4
Well, with this, we will need to use FileWriter. We can overwrite the original file with the new text we want.
By the way, both FileWriter and Reader constructors throw IOException, so you have to handle it. (try, catch)Java Code:FileWriter out = new FileWriter("hello.txt"); out.write(//new value of x); out.close();
- 01-31-2008, 08:42 PM #5
Member
- Join Date
- Jan 2008
- Posts
- 3
- Rep Power
- 0
Thanks again, I've got it all working now :D
- 02-01-2008, 12:16 AM #6
Similar Threads
-
Axis Client accessing data on .Net webservice
By cfacile666 in forum Web FrameworksReplies: 3Last Post: 09-02-2008, 11:35 AM -
Accessing a file randomly
By Java Tip in forum Java TipReplies: 0Last Post: 11-10-2007, 08:15 PM -
Accessing client file system
By revathi17 in forum New To JavaReplies: 1Last Post: 10-17-2007, 10:17 AM -
Packaging and accessing data files
By todd in forum Advanced JavaReplies: 1Last Post: 08-01-2007, 12:27 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks