How to read the additional lines in a text file - java

I have an assignment to create a "map" which is really an array that contains rooms. In the rooms there are artifacts that you can look at or examine and put into your inventory or "backpack". You are also able to save and restore your placement on the map, along with the artifact locations and your inventory. The save function saves it to a text file with the location, artifacts, and inventory. The problem that I am running into is trying to get the artifact data from the text file to restore on the program. I have no problem loading the location, but can not load any artifacts. While running the debugger it skips over the line. Here is the piece of code I am trying to work.
File fileRestore = new File("C:\\Users\\mike\\Desktop\\GCPU.txt");
try
{
FileReader reader = new FileReader(fileRestore);
BufferedReader buffer = new BufferedReader(reader);
String line = buffer.readLine();
while (line !=null)
{
String[] contents = line.split(",");
String key = contents[0];
if (key.equals("StartLocation"))
{
row = Integer.parseInt(contents[1]);
col = Integer.parseInt(contents[2]);
}
key = contents [1];
if (key.equals("Artifact"))
{
String name = contents [1];
row = Integer.parseInt(contents [2]);
col = Integer.parseInt(contents [3]);
if (name.equals("vending"))
map.rooms[row][col].contents = map.vending;
if (name.equals("beaker"))
map.rooms[row][col].contents = map.beaker;
if (name.equals("gameboy"))
map.rooms[row][col].contents = map.gameboy;
if (name.equals("paper"))
map.rooms[row][col].contents = map.paper;
if (name.equals("trees"))
map.rooms[row][col].contents = map.trees;
if (name.equals("desk"))
map.rooms[row][col].contents = map.desk;
if (name.equals("brewer"))
map.rooms[row][col].contents = map.brewer;
if (name.equals("statue"))
map.rooms[row][col].contents = map.statue;
}
Here is the text file that I am reading from:
StartLocation,0,2
Artifact,Eerie statue,2,0
Artifact,A small redwood sprout,3,0
Artifact,Gameboy Color,0,1
Artifact,Lapdesk,1,1
Artifact,A piece of paper,2,1
Artifact,Industrial coffee maker,1,3
So to reiterate my question, how am I able to read the Artifact line from the text along with the StartLocation line?
Thank you for taking the time to read this.

You are only reading once from the file. Replacing these two lines:
String line = buffer.readLine();
while (line !=null)
...
With something like so:
String line = "";
while((line = buffer.readLine()) != null)
...
Should allow you to read the next line each time the while loop iterates.
Alternatively, you could also have a line = buffer.readLine() just before your closing brace for the while loop. This approach is also valid, however, judging by the tutorials I went through, simply less popular.

String line = buffer.readLine();
should be inside the while loop. It is being executed only once.
Although make sure to modify initial value of line and the loop condition such that the loop starts .
Good luck.

String line = buffer.readLine(); will skip over the first line.
2.
if (key.equals("StartLocation"))
{ row = Integer.parseInt(contents[1]);
col = Integer.parseInt(contents[2]);
}
will fail because key = " StartLocation". there is a space in your
text file. use line=line.trim() to remove unnecessary characters.
3. Your program will read only 1 line.

Related

Java, CSV, Getting error if do not click on Save button of the csv file

This is my code
public double myMethod(String name)
{
double result = 0.0;
String path = "/Users/T/Desktop/Training/MyFolder/";
int maxColumn = 0;
BufferedReader br = null;
ArrayList findMaxColumn = new ArrayList();
String line = "";
try
{
br = new BufferedReader(new FileReader(path+name));
while((line = br.readLine())!= null)
{
findMaxColumn.add(temp.split(",").length);
}
maxColumn = getMaxNumber(findMaxColumn);
CSVReader reader = new CSVReader(new FileReader(path+name));
List<String[]> myData = reader.readAll();
for(int i = 0 ; i < maxColumn;i++)
{
for (String[] lineData : myData)
{
String value= lineData[i];
The problem is, I have a csv file (generated from other method and stored in MyFolder) and when I run this code, I got an error "ArrayIndexOutOfBoundsException: 1" at String value= lineData[i]. But, if I open my csv file and click on save button (or make some changes for a value eg 0 to 1 etc) and close it before I run this code then it will be fine when I run it. That's weird!!! Could anyone explain to me why I have to open the csv file and make some changes(just click on save button or change a value to another) to ignore the problem and how to fix it?
Check that your encoding when you save the file is the same encoding with the one you use when you read the file. It may well be that you are saving, for example, in UTF8 and reading the file as it would be UTF16.
This fits what you describe (if opening and saving the file before reading it, then it works) as well as the ""ArrayIndexOutOfBoundsException: 1"" - showing that the "split" method did not find any separator (the comma) thus return a single string.
It would also help if using a debugger to check what is in your array just-to-be-added-to findMaxColumn after splitting. Easier to debug if you use a local variable to store the result of split before adding:
while((line = br.readLine())!= null)
{
String splitResult[]=temp.split(","); // easier to examine
findMaxColumn.add(splitResult);
}

Read only values from aText file

I've a text file which has values given as =
FORMNAME1=Cat
CONTROL ID=6
DATA WIDTH=20
LABEL WIDTH = 30
LABEL ALIGN = R
FORMNAME2= bat
CONTROL ID=5
DATA WIDTH=20
LABEL WIDTH = 30
LABEL ALIGN = R
FORMNAME3= rat
CONTROL_ID3=10
DATAWIDTH3=20
LABELWIDTH3 = 30
LABEL_ALIGN3 = R
How to read only the values stored in each line i.e only the data after = using JAVA?
Read the file as shown here, and use String.split() in each line to get the value:
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
String value = line.split("=")[1];
System.out.println(value);
}
}
EXPLANATION: to read the file, is well explained in question I linked
lets see: you are processing each line of the file INDIVIDUALLY, then the content of the file (just one line) arrives to this part of the code, but what is doing this line?
String value = line.split("=")[1];
line variable, in first iteration will contain:
FORMNAME1=Cat
split("=") will create an array like this
[0] FORMNAME1
[1] Cat
so the line is assigning the value of position 1 (Cat) to the variable value
String value = "Cat";
Second iteration will do same but different content:
line = "CONTROL ID=6"
so
line.split("=")
will result
[0] CONTROL ID
[1] 6
And
// be careful is a string representing "6"
// not the numerical value 6 as int or double!!!!!
String value = "6";
and so on....
EXTRA TIP:
use String.valueOf() if you want to extract numerical values

How to access values of a line, while reading in a text file in Java

I am trying to load in two files at the same time but also access the first gps1 file. I want to access the gps1 file line-by-line and depending on the sentence type which I will explain later I want to do different stuff with that line and then move to the next line.
Basically gps1 for example has multiple lines but each line falls under a couple of catagories all starting with $GPS(then other characters). Some of these types have a time stamp which I need to collect and some types do not have a time stamp.
File gps1File = new File(gpsFile1);
File gps2File = new File(gpsFile2);
FileReader filegps1 = new FileReader(gpsFile1);
FileReader filegps2 = new FileReader(gpsFile2);
BufferedReader buffer1 = new BufferedReader(filegps1);
BufferedReader buffer2 = new BufferedReader(filegps2);
String gps1;
String gps2;
while ((gps1 = buffer1.readLine()) != null) {
The gps1 data file is as follows
$GPGSA,A,3,28,09,26,15,08,05,21,24,07,,,,1.6,1.0,1.3*3A
$GPRMC,151018.000,A,5225.9627,N,00401.1624,W,0.11,104.71,210214,,*14
$GPGGA,151019.000,5225.9627,N,00401.1624,W,1,09,1.0,38.9,M,51.1,M,,0000*72
$GPGSA,A,3,28,09,26,15,08,05,21,24,07,,,,1.6,1.0,1.3*3A
Thanks
I don't really understand the problem you are facing but anyway, if you want to get your lines content you can use a StringTokenizer
StringTokenizer st = new StringTokenizer(gps1, ",");
And then access the data one by one
while(st.hasMoreToken)
String s = st.nextToken();
EDIT:
NB: the first token will be your "$GPXXX" attribute

read data from a file in java

I have a text file in the following format:
Details.txt
The file is a .txt file. I want to read course title from this file and print corresponding textbook and instructor information. But i am not sure about what process to follow ? storing the information in an array won't be efficient! How should i proceed ? NOTE: I can't change the info in the file, it should not be changed!! obviously the file will be read by the following code:
File newFile=new File("C:/details");
but how should i extract the data from this file according to the labels course title, textbook and instructor!?
First read the file correctly line by line, and search for your entered course title, lets consider "Java"
Now you hit your title and you know you need 3 consecutive lines from your file as all information related to that title are there.
if(str.startsWith(title)); { // for title = "Java"
line1 = 1st line // contains ISBN and First Name
line2 = 2nd line // Title and Last Name
line3 = 3rd line // Author and Department
line4 = 4th line // Email
break; // this will take you out of while loop
}
Now on those four lines do string operations and extract your data as you need and use it.
I am home so I can't give you exact code. But if you follow this it will solve your issue. Let me know if any problem you got while doing this.
Follow this to get some info on String operations
Use String Tokenizer and separate each string and then store them in a Linked List or Array List. Have Separate List for each title like course title, instructor etc. and then print them
//Find the directory for the SD Card using the API
//*Don't* hardcode "/sdcard"
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard,"file.txt");
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
}
catch (IOException e) {
//You'll need to add proper error handling here
}
//Find the view by its id
TextView tv = (TextView)findViewById(R.id.text_view);
//Set the text
tv.setText(text);
you can use FileUtils.readFileToString(new File(""C:/details.txt");
Now you can extract the required data based on your wish
Use Scanner class
Scanner s=new Scanner(new File("C:/Details.txt"));
while(s.hasNext())
{
System.out.println(s.nextLine());
}
if you want in work by word then use String Tokenizer
see this article

How to read and update row in file with Java

currently i creating a java apps and no database required
that why i using text file to make it
the structure of file is like this
unique6id username identitynumber point
unique6id username identitynumber point
may i know how could i read and find match unique6id then update the correspond row of point ?
Sorry for lack of information
and here is the part i type is
public class Cust{
string name;
long idenid, uniqueid;
int pts;
customer(){}
customer(string n,long ide, long uni, int pt){
name = n;
idenid = ide;
uniqueid = uni;
pts = pt;
}
FileWriter fstream = new FileWriter("Data.txt", true);
BufferedWriter fbw = new BufferedWriter(fstream);
Cust newCust = new Cust();
newCust.name = memUNTF.getText();
newCust.ic = Long.parseLong(memICTF.getText());
newCust.uniqueID = Long.parseLong(memIDTF.getText());
newCust.pts= points;
fbw.write(newCust.name + " " + newCust.ic + " " + newCust.uniqueID + " " + newCust.point);
fbw.newLine();
fbw.close();
this is the way i text in the data
then the result inside Data.txt is
spencerlim 900419129876 448505 0
Eugene 900419081234 586026 0
when user type in 586026 then it will grab row of eugene
bind into Cust
and update the pts (0 in this case, try to update it into other number eg. 30)
Thx for reply =D
Reading is pretty easy, but updating a text file in-place (ie without rewriting the whole file) is very awkward.
So, you have two options:
Read the whole file, make your changes, and then write the whole file to disk, overwriting the old version; this is quite easy, and will be fast enough for small files, but is not a good idea for very large files.
Use a format that is not a simple text file. A database would be one option (and bear in mind that there is one, Derby, built into the JDK); there are other ways of keeping simple key-value stores on disk (like a HashMap, but in a file), but there's nothing built into the JDK.
You can use OpenCSV with custom separators.
Here's a sample method that updates the info for a specified user:
public static void updateUserInfo(
String userId, // user id
String[] values // new values
) throws IOException{
String fileName = "yourfile.txt.csv";
CSVReader reader = new CSVReader(new FileReader(fileName), ' ');
List<String[]> lines = reader.readAll();
Iterator<String[]> iterator = lines.iterator();
while(iterator.hasNext()){
String[] items = (String[]) iterator.next();
if(items[0].equals(userId)){
for(int i = 0; i < values.length; i++){
String value = values[i];
if(value!=null){
// for every array value that's not null,
// update the corresponding field
items[i+1]=value;
}
}
break;
}
}
new CSVWriter(new FileWriter(fileName), ' ').writeAll(lines);
}
Use InputStream(s) and Reader(s) to read file.
Here is a code snippet that shows how to read file.
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("c:/myfile.txt")));
String line = null;
while ((line = reader.readLine()) != null) {
// do something with the line.
}
Use OutputStream and Writer(s) to write to file. Although you can use random access files, i.e. write to the specific place of the file I do not recommend you to do this. Much easier and robust way is to create new file every time you have to write something. I know that it is probably not the most efficient way, but you do not want to use DB for some reasons... If you have to save and update partial information relatively often and perform search into the file I'd recommend you to use DB. There are very light weight implementations including pure java implementations (e.g. h2: http://www.h2database.com/html/main.html).

Categories