Turning a string in from a text file into a variable identifier - java

Right, so I've seen a lot of these questions phrased in a similar way but none of these are specifically to what I need. I have a text file like so:
~Jerry
10/patio/*
11/bathroom/*
23/home/*
~Jeff
28/patio/*
84/bathroom/*
33/home/*
I can read these fine. What I'm trying to accomplish is to take the lines that start with '~' change them into variable names and supply them with all lines below it that don't start with '~'.
Therefore, I'd like to be able to supply the .txt, take the name Jerry and instantiate it as:
try(BufferedReader br = new BufferedReader(new FileReader(filepath))) {
for(String line; (line = br.readLine()) != null; )
{
if(line.charAt(0) == '~'){
line.replace("~","");
int[] line = new int[];
}
else{
//add the line to the Jerry array
}
}
}
catch(Exception e){
System.out.println(e);
}
Is there a capability for using stored string to declare new variables? or at least provide the illusion of declaring a new variable so that it can be used with other methods? Or do I need to hard code the declaration in and use a case statement or the like?

Related

assigning properties to strings in text file

Hopefully my explanation does me some justice. I am pretty new to java. I have a text file that looks like this
Java
The Java Tutorials
http://docs.oracle.com/javase/tutorial/
Python
Tutorialspoint Java tutorials
http://www.tutorialspoint.com/python/
Perl
Tutorialspoint Perl tutorials
http://www.tutorialspoint.com/perl/
I have properties for language name, website description, and website url. Right now, I just want to list the information from the text file exactly how it looks, but I need to assign those properties to them.
The problem I am getting is "index 1 is out of bounds for length 1"
try {
BufferedReader in = new BufferedReader(new FileReader("Tutorials.txt"));
while (in.readLine() != null) {
TutorialWebsite tw = new TutorialWebsite();
str = in.readLine();
String[] fields = str.split("\\r?\\n");
tw.setProgramLanguage(fields[0]);
tw.setWebDescription(fields[1]);
tw.setWebURL(fields[2]);
System.out.println(tw);
}
} catch (IOException e) {
e.printStackTrace();
}
I wanted to test something so i removed the new lines and put commas instead and made it str.split(",") which printed it out just fine, but im sure i would get points taken off it i changed the format.
readline returns a "string containing the contents of the line, not including any line-termination characters", so why are you trying to split each line on "\\r?\\n"?
Where is str declared? Why are you reading two lines for each iteration of the loop, and ignoring the first one?
I suggest you start from
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
and work from there.
The first readline gets the language, the second gets the description, and the third gets the url, and then the pattern repeats. There is nothing to stop you using readline three times for each iteration of the while loop.
you can read all the file in a String like this
// try with resources, to make sure BufferedReader is closed safely
try (BufferedReader in = new BufferedReader(new FileReader("Tutorials.txt"))) {
//str will hold all the file contents
StringBuilder str = new StringBuilder();
String line;
while ((line = in.readLine()) != null) {
str.append(line);
str.append("\n");
} catch (IOException e) {
e.printStackTrace();
}
Later you can split the string with
String[] fields = str.toString().split("[\\n\\r]+");
Why not try it like this.
allocate a List to hold the TutorialWebsite instances.
use try with resources to open the file, read the lines, and trim any white space.
put the lines in an array
then iterate over the array, filling in the class instance
the print the list.
The loop ensures the array length is a multiple of nFields, discarding any remainder. So if your total lines are not divisible by nFields you will not read the remainder of the file. You would still have to adjust the setters if additional fields were added.
int nFields = 3;
List<TutorialWebsite> list = new ArrayList<>();
try (BufferedReader in = new BufferedReader(new FileReader("tutorials.txt"))) {
String[] lines = in.lines().map(String::trim).toArray(String[]::new);
for (int i = 0; i < (lines.length/nFields)*nFields; i+=nFields) {
TutorialWebsite tw = new TutorialWebsite();
tw.setProgramLanguage(lines[i]);
tw.setWebDescription(lines[i+1]);
tw.setWebURL(lines[i+2]);
list.add(tw);
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
list.forEach(System.out::println);
A improvement would be to use a constructor and pass the strings to that when each instance is created.
And remember the file name as specified is relative to the directory in which the program is run.

Store info from .txt file as variables

I am trying to get my code to read from a text file and store what's in it as variables..strings and doubles...to use later. I have no problem getting it to return the info.
This is what's in the .txt file:
circle 5
triangle 3
square 10
sphere 5
cube 4
tetrahedron 8
and for my code I have:
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(
"src/Data.txt"));
String line = reader.readLine();
while (line != null) {
System.out.println(line);
// read next line
line = reader.readLine();
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
Store your text contents in a hash map, in the following code, I name it "vars". The hashMap vars contains your variables as key,value pairs.
If you need to get the value of any of the variables, you simple write:
vars.get(key);
so for example to get the value of circle, you write:
vars.get("circle");
This is your code after modifying it with a hashmap to store variables.
BufferedReader reader;
HashMap<String,Double> vars = new HashMap<>();
try {
reader = new BufferedReader(new FileReader(
"src/Data.txt"));
String line = reader.readLine();
while (line != null) {
System.out.println(line);
String[] lineVars = line.split(" ");
vars.put(lineVars[0],Double.parseDouble(lineVars[1]));
// read next line
line = reader.readLine();
}
reader.close();
}catch (IOException e) {
e.printStackTrace();
}
As far as I know, it is not possible to construct a variable name. You can't read "circle" and assign that as a variable name. You can store these as a [key,value] pair using a HashMap<String,Double> to store them as a pair.
The first part would be to split the lines, using String.split, to separate variable name and value. If you know in advance which variables you expect in the text file, you can declare those variables and use a switch statement to decide which variable the read name corresponds to, and assign the value accordingly. Otherwise, a HashMap or something similar could be used to store the names and values found in the file.

How To Read A Specific Part Of A Line In A Text File In Java?

I have a text file in which I have written some information line by line like this:
name|Number|amount|PIN
How can I read back data In a way that (for example) I will be able to use just the "name" part in a method?
The sample code is shown in the image below.
in the beginning declare a List to collect the accounts:
import java.util.ArrayList;
...
public Account[] inReader() { //BTW: why do you pass an Account[] here?
ArrayList accountList = new ArrayList();
...
}
replace the for(String records : dataRecords) {...} with
String name = dataRecords[0];
String cardNumber = dataRecords[1];
int pin = Integer.parseInt(dataRecords[2]); //to convert the String back to int
double balance = Double.parseDouble(dataRecords[3]);
Account account = new Account(name, cardNumber, pin, balance);
accountList.add(account);
because you already proceed record by record (while ((line = br.readLine())!=null) {...})
in the end return accountList.toArray(new Account[0]);
You can read the text line by line and then use the "|" delimiter to separate the columns.
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
stream.forEach(System.out::println);
}
You could read the file line-by-line and split on the delimiter '|'.
The following example assumes the filepath is in args[0] and would read then output the name component of the input:
public static void main(String[] args) {
File file = new File(args[0]);
BufferedReader br = new BufferedReader(new FileReader(file));
while(String line = br.readLine()) != null) {
String[] details = line.split("|");
System.out.println(details[0]);
}
}
As mentioned in the comment above, you can simply split the line on your delimiter, |, and go from there.
Something like:
public class Account {
// ...
public static Account parseLine(String line) {
String[] split = line.split("|");
return new Account(split[0], split[1], split[2], split[3]);
}
}
should work fine (assuming you have a constructor which takes the four things you're putting in). If your Account class has more information than this, you can create an AccountView or similarly named class which does only contain the details you have available here. With this, just iterate line by line, parse your lines to one of these Objects, and use it's properties (including the already available getters) when calling other methods which need name, etc.
First, you need to read the whole content of the file or line by line.
Then, for each line you need to create a function to split the line text by a configurable delimiter. This function can receive the column number and it should return the needed value. For example: extractData(line, 0) should return 'name', extractData(line, 2) should return 'amount' etc.
Also, you need some validation: what if there are only 3 columns and you expect 4? You can throw and exception or you can return null/empty.
There are many possible ways to do it. One of them is to make an object that will hold the data. Example since you know that your data will always have name, number, amount and pin then you can make a class like this:
public class MyData {
private String name;
private String number;
private double amount;
private String pin;
// Add getters and setters below
}
Then while reading the text file you can make a list of MyData and add each data. You can do it like this:
try {
BufferedReader reader = new BufferedReader(new FileReader("path\file.txt"));
String line = reader.readLine();
ArrayList<MyData> myDataList = new ArrayList<MyData>();
while (line != null) {
String[] dataParts = line.split("|"); // since your delimiter is "|"
MyData myData = new MyData();
myData.setName(dataParts[0]);
myData.setNumber(dataParts[1]);
myData.setAmount(Double.parseDouble(dataParts[2]));
myData.setPin(dataParts[3]);
myDataList.add(myData);
// read next line
line = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
Then you can use the data like this:
myDataList.get(0).getName(); // if you want to get the name of line 1
myDataList.get(1).getPin(); // if you want to get the pin of line 2
You can convert the file into a csv file and use a library specific for reading csv files, e.g. OpenCSV. This will give you more flexibility in handling the data in the file.

Reading from a CSV file into an array

I am making a program that has an array of people. The people have different amounts of info for instance they all have a first name, last name, type, gender. The first issue I have is some also have email and some have a image (using Icon) and some have both of them.
I need to read these pieces of data in and then display them, it is for a college class and the teacher was basically like figure it out.. I have read the API and numerous articles and can't seem to get it to work. Can someone give me a push in the right direction?
I am not looking for you to hand me the answers just a little help.
Read the file line by line and split line with ,.
// you need to create a pojo to hold all the user info.
List<UserObject> users = new ArrayList<UserObject>();
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
String[] userinfos = line.split(",");
UserObject newUser = new UserObject();
//set the mandatory attributes here
if (userinfos.length > 4) {
// you have the extra fields here.
// set the extra fields to user here
}
users.add(newUser);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
One problem with this is first name or last name might have commas with in them. I suggest you to use any third party csv parser like Open Csv.

BufferedReader replacing in loop

I'm trying to make this work, I don't understand why it doesn't work since it makes sense to me, but it doesn't make sense to java it seems.
As you read the code, what I expect is _NAME to be replaced by TEST while maintaining the same structure of the text (keeping \n) to save it later(not done yet)
I also stored it using ArrayList, but the replace never took off either, so I'm clueless
try {
BufferedReader reader = new BufferedReader (new InputStreamReader (
new FileInputStream (temp), "utf-8"));
String line = reader.readLine();
StringBuffer text = new StringBuffer();
while(line != null) {
line.replace("[_NAME]", "TEST");
Logger.info(line);
line = reader.readLine();
}
reader.close();
} catch(FileNotFoundException ex) {
} catch(UnsupportedEncodingException ex) {
} catch(IOException ex ) {}
The correct line is
line = line.replace("_NAME", "TEST");
If you use brackets, you are specifying the characters as individual matches (_, N, A, M and E), and you want to replace the whole match.
Second, the replace method return a new String that contains the modified String. Remember that Strings in Java are immutable, so no method that modifies a String would modify the input object, they will always return a new object.
One possible problem is the fact that you have [] around _NAME but I'm going to go with the "you forgot that replace returns the new string instead of changing it in-situ" option. See here.
In other words, it should changed from:
line.replace ( ...
to:
line = line.replace ( ...

Categories