What is the best way to assign values to variables of various data types from reading a file (while importing as few things as possible and making use of the simplest code)? I need to write a program which can assign values from a .dat file, if that's relevant. If you could also provide some examples and explanations of such, you will be mentally extolled. Thanks.

I suppose you have already figured out how to write to a file, or you plan to manually make the file. The way I would go about doing this is using a BufferedReader.

Here is some code:

BufferedReader in=new BufferedReader(new FileReader("C:\\users\\sample.dat")); //creates BufferedReader to get value
String line1=in.readLine();//uses reader to save value to String line1
in.close();//closes connection to file
value = Integer.parseInt(line1.trim()); //optional, just to parse if the value is an int

Hope this helps :D

What is the ".dat" file? That extension doesn't really mean anything and many programs store many different types of things using that extension in many different formats. If know what is saved, and, more importantly, how it is saved, we could give you a better answer. P.S. A BufferedReader will only work "properly" for text files.

I will be storing variables of type string, boolean, and int. An example of input given in my assignment:

planet true 5 2
station 5 8

Okay? So how are you saving that? With a RandomAccessFile? A DataOutputStream? An ObjectOutputStream? A FileWriter?

A .dat file is perfectly fine. .dat files can take the same things as .txt files, therefore it can take strings, ints, etc.

A .dat file is perfectly fine. .dat files can take the same things as .txt files, therefore it can take strings, ints, etc.

Yes it can, but that's not quite the point. The point is that how it is written will greatly affect, of course, how it is to be read.

But the book I'm reading from uses Scanner, is it still basically the same thing though?

That also does nothing other than read bytes and interpret them as characters (i.e. text files and text files only). If the data is not being saved as simple text written using a filewriter (or fileoutputstream), but rather as a data or object outputstream you won't be able to use that.

Since the OP doesn't feel the need to tell us exactly what the .dat file consists of (he has told us the "data" that may be in it, but not how that is represented in the file) I no longer fell the need to help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.