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.
Related
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?
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.
I have a text file that contains the following:
example.txt
#ignore
#ignore line
#ignore line again
1234567
8940116
12131415
I want to read in the example.txt file into eclipse and add the data into a hashmap. I want the list to be arranged in numerical order and I want it to ignore any comments(any text with #) in the text file. I would like to print the hashmap as follows:
output:
1234567
8940116
12131415
You don't need a hashmap for storing just Strings. Maps are for key value pairs. If you want to put each line from file into a collection use Lists. ArrayLists, LinkedList maintain insertion order. You can use any of them. If you want sorted list you can use TreeList.
BufferedReader reader;
List<String> list = new ArrayList<String>();
try {
reader = new BufferedReader(new FileReader(
"example"));
String line = reader.readLine();
while (line != null) {
if(!line.startsWith("#"){
list.add(line);
}
line = reader.readLine();
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
Thr purpose of a Map is to store pairs Key/Value, for a single collection you may use a List it's far more efficient, the printing part is you job whatever the type of collection is
List<String> values = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader("filename"))) {
String line;
while ((line = reader.readLine()) != null) {
if (!line.startsWith("#")) {
values.add(line);
}
}
} catch (IOException e) {
e.printStackTrace();
}
for (String v : values)
System.out.println(v);
I have an assignment where i have to read a CSV file containing data with some repeated lines. How to remove the duplicate values and print only the unique values in Eclipse
The data is similar to this:-
1,Ron,1234,ABC,12
2,Harry,4125,DEF,14
3,Kent,1786,GHI,15
1,Ron,1234,ABC,12
2,Harry,4125,DEF,14
String csvFile = "csv.csv";
BufferedReader br = null;
String line = "";
HashSet<String> lines = new HashSet<>();
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
if (lines.add(line)) {
System.out.println(line);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
It may help you
My suggestion is to use the following strategy:
1st step: create a HashMap http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html
where you will save each line of the CSV you read. You will save in a hashmap because Hashmap will NOT accept a key that is like another. So, each line you will read, you will save in the hashmap as a KEY!
So, the logic is: Try to save the line you just read as a Key. IF it works, print that line. If it didn't work, discard the line and read the next one.
Got it?
2nd step:
Use a BufferedReader http://docs.oracle.com/javase/7/docs/api/index.html?java/io/BufferedReader.html to read line by line of the CSV.
Get each line of the CSV with the BufferedReader with readLine().
It will save the line you are reading in a String
That's it.
So, here is the overview of the entire code:
1- Read each line of the code with BufferedReader.readLine()
2- Get that string you got from readLine and try to add to your Hashmap as the Key of the hashmap: if it works, print the String. If it doesn't work, discard the string;
3- Read the next line.
I have a csv file that currently has 20 lines of data.
The data contains employee info and is in the following format:
first name, last name, Employee ID
So one line would like this: Emma, Nolan, 2
I know how to write to the file in java and have all 20 lines print to the console, but what I'm not sure how to do is how to get Java to print one specific line to the console.
I also want to take the last employee id number in the last entry and have java add 1 to it one I add new employees. I thinking this needs to be done with a counter just not sure how.
You can do something like this:
BufferedReader reader = new BufferedReader(new FileReader(<<your file>>));
List<String> lines = new ArrayList<>();
String line = null;
while ((line = reader.readLine()) != null) {
lines.add(line);
}
System.out.println(lines.get(0));
With BufferedReader you are able to read lines directly. This example reads the file line by line and stores the lines in an array list. You can access the lines after that by using lines.get(lineNumber).
You can read text from a file one line at a time and then do whatever you want to with that line, print it, compare it, etc...
// Construct a BufferedReader object from the input file
BufferedReader r = new BufferedReader(new FileReader("employeeData.txt"));
int i = 1;
try {
// "Prime" the while loop
String line = r.readLine();
while (line != null) {
// Print a single line of input file to console
System.out.print("Line "+i+": "+line);
// Prepare for next loop iteration
line = r.readLine();
i++;
}
} finally {
// Free up file descriptor resources
r.close();
}
// Remember the next available employee number in a one-up scheme
int nextEmployeeId = i;
BufferedReader reader =new BufferedReader(new FileReader("yourfile.csv"));
String line = "";
while((line=reader.readLine())!=null){
String [] employee =line.trim().split(",");
// if you want to check either it contains some name
//index 0 is first name, index 1 is last name, index 2 is ID
}
Alternatively, If you want more control over read CSV files then u can think about CsvBeanReader that will give you more access over files contents..
Here is an algorithm which I use for reading csv files. The most effective way is to read all the data in the csv file into a 2D array first. It just makes it a lot more flexible to manipulate the data.
That way you can specify which line of the file to print to the console by specifying it in the index of the array and using a for. I.e: System.out.println(employee_Data[1][y]); for record 1. y is the index variable for fields. You would need to use a For Loop of course, to print every element for each line.
By the way, if you want to use the employee data in a larger program, in which it may for example store the data in a database or write to another file, I'd recommend encapsulating this entire code block into a function named Read_CSV_File(), which will return a 2D String array.
My Code
// The return type of this function is a String.
// The CSVFile_path can be for example "employeeData.csv".
public static String[][] Read_CSV_File(String CSVFile_path){
String employee_Data[][];
int x;
int y;
int noofFields;
try{
String line;
BufferedReader in = new BufferedReader(new FileReader(CSVFile_path));
// reading files in specified directory
// This assigns the data to the 2D array
// The program keeps looping through until the line read in by the console contains no data in it i.e. the end of the file.
while ( (( line = in.readLine()) != null ){
String[] current_Record = line.split(",");
if(x == 0) {
// Counts the number of fields in the csv file.
noofFields = current_Record.length();
}
for (String str : values) {
employee_Data[x][y] = str;
System.out.print(", "+employee_Data[x][y]);
// The field index variable, y is incremented in every loop.
y = y + 1;
}
// The record index variable, x is incremented in every loop.
x = x + 1;
}
// This frees up the BufferedReader file descriptor resources
in.close();
/* If an error occurs, it is caught by the catch statement and an error message
* is generated and displayed to the user.
*/
}catch( IOException ioException ) {
System.out.println("Exception: "+ioException);
}
// This prints to console the specific line of your choice
System.out.println(("Employee 1:);
for(y = 0; y < noofFields ; y++){
// Prints out all fields of record 1
System.out.print(employee_Data[1][y]+", ");
}
return employee_Data;
}
For reading large file,
log.debug("****************Start Reading CSV File*******");
copyFile(inputCSVFile);
StringBuilder stringBuilder = new StringBuilder();
String line= "";
BufferedReader brOldFile = null;
try {
String inputfile = inputCSVFile;
log.info("inputfile:" + inputfile);
brOldFile = new BufferedReader(new FileReader(inputfile));
while ((line = brOldFile.readLine()) != null) {
//line = replaceSpecialChar(line);
/*do your stuff here*/
stringBuilder.append(line);
stringBuilder.append("\n");
}
log.debug("****************End reading CSV File**************");
} catch (Exception e) {
log.error(" exception in readStaffInfoCSVFile ", e);
}finally {
if(null != brOldFile) {
try {
brOldFile.close();
} catch (IOException e) {
}
}
}
return stringBuilder.toString();