The csv file I am trying to parse contains various samples with several lines per sample. For example, there are 10 lines with the same sample name "S1" and I need to get the CT value from each line. I am trying to combine the CT values (differentiated by the Target Name) to create a Sample class for each sample. I am able to parse the file, but I am having a hard time getting it to loop through and gather the right data.
The constructor for my Sample class has 11 parameters, one for the sample name and 10 for the CT values.
After thinking about it for a long time I tried gathering all of the information I need in an ArrayList of String arrays. This didn't help too much because I now don't know how to gather the information together to create and instance of my Sample class. Here's what I tried:
public void parseCSV(){
String line = "";
String csvSplitBy = ",";
try
{
Scanner scanner = new Scanner(new FileReader("/Users/Neema/Desktop/testData.csv"));
String[] data;
while (scanner.hasNextLine())
{
line = scanner.nextLine();
data = line.split(csvSplitBy);
if (data.length > 0 && data[0].equals("Well"))
{
while (scanner.hasNextLine())
{
line = scanner.nextLine();
data = line.split(csvSplitBy);
if (data.length > 4)
{
String sampleName = data[3];
String dataType = data[4];
String ctValue = data[11];
String[] gatheredData = {sampleName, dataType, ctValue};
parsedData.add(gatheredData);
}
}
}
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
Here is the csv file, testData2
Thanks for any help!
I think I understand. What you need is a Sample Factory.
class SampleFactory {
String sampleName;
List<TargetAndValue> sampleList;
SampleFactory(String sampleName)
{
this.sampleName = sampleName;
}
class TargetAndValue{
String dataType;
String ctValue;
TargetAndValue(dataType, ctValue)
{
this.dataType = dataType;
this.ctValue = ctValue;
}
}
void addCtValue(dataType, ctValue) { //Instantiate a new TargetAndValue class }
Sample build(){ //Construct your Sample here }
}
Than what you need is a list of SampleFactories. As you parse each line you search for the SampleFactory that has the right sampleName, and add your data point. Once you have parsed everything use your factory to spit out your Sample objects.
Try it with a map. For example
public void parseCSV(){
String line = "";
String csvSplitBy = ",";
Map<String,List<String>> mapofSamples = new TreeMap<>(); // import java.util.Map; import java.util.TreeMap;
try
{
Scanner scanner = new Scanner(new FileReader("/Users/Neema/Desktop/testData.csv"));
String[] data;
while (scanner.hasNextLine())
{
line = scanner.nextLine();
data = line.split(csvSplitBy);
if (data.length > 0 && data[0].equals("Well"))
{
while (scanner.hasNextLine())
{
line = scanner.nextLine();
data = line.split(csvSplitBy);
if (data.length > 4)
{
if(!mapofSamples.containsKey(data[3])){ // if the map does not already contain the sample name add this name and a list with the value
mapofSamples.put(data[3],new ArrayList(){{add(data[11]);}} );
}
else{
mapofSamples.get(data[3]).add(data[11]); // else just add the value to the corresponding sample names value list
}
}
}
}
}
for(String key: mapofSamples.keySet()){ // check if it prints the right keys and values
System.out.println("sample :" + key);
System.out.println("values :" + mapofSamples.get(key));
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
Related
On Java Ive make a simple program with search bar. Ive also a CSV File 'file.csv' that contains this:
"ID","FIRSTNAME","LASTNAME"
"JM1","Jean","Martial"
"AD1","Audrey","Dubois"
"BX1","Bertrand","Xavier"
I can open the file on Java with this line.
String file = "C:\\file.csv";
To verify if file exists I use this line.
if(new File(file).exists()) {
JOptionPane.showMessageDialog(frame, "Fichier ouvert succes");
}
Now I want to parse the file to extract AD1 and display true if exist or false if not exists. Ive declared Scanner for this, but i dont know how to setup for this.
Scanner scanner = null;
try {
scanner = new Scanner(new File(file));
scanner.useDelimiter(coma_delimiter);
while(scanner.hasNext()) {
String s1= scanner.next();
System.out.print(s1 +" ");
if(s1.equals(search_field.getText())) {
System.out.print("OKOK");
} else {
System.out.println("NOK");
}
}
} catch (FileNotFoundException fe) {
fe.printStackTrace();
} finally {
scanner.close();
}
Here the search_field is a JTextField.
You are not reading your file line by line. What you are actually supposed to do is get a line, split it, remove the double quotes and compare to your string. Or you can wrap your input string in a double quote and just compare with the string after splitting. For this try the following code:
Scanner scanner = null;
try {
scanner = new Scanner(new File(file));
String s1 = null;
String id= null;
String[] tempArr = null;
String searchStr = "\""+search_field.getText()+"\"";
System.out.print("searchStr = " + searchStr );
while(scanner.hasNext()) { // While there are more lines in file
s1= scanner.nextLine();
tempArr = s1.split(","); // use coma_delimiter instead coma_delimiter if coma_delimiter=","
id = (tempArr != null && tempArr.length > 0? tempArr[0] : null);
System.out.print("ID = " + id);
if(id != null && id.equals(searchStr)) {
System.out.print("OKOK");
break; // quit the loop searchStr is found
} else {
System.out.println("NOK");
}
}
} catch (FileNotFoundException fe) {
fe.printStackTrace();
} finally {
scanner.close();
}
You may want to use Apache Commons CSV instead as this is designed to work with csv file, straight from their page is the below example
Reader in = new FileReader("path/to/file.csv");
Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(in);
for (CSVRecord record : records) {
String lastName = record.get("Last Name");
String firstName = record.get("First Name");
}
where "Last Name" and "First Name" are all column names.
This way you can clearly check on which column your string is.
Maven dependency below:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
<version>1.5</version>
</dependency>
You could also use the stream API to process each line individually. It may also have methods that would make this more elegant than my answer.
final String ENCL = "\"";
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
Map<String, List<String>> ans = stream.map(s -> {
String[] split = s.split(",");
if(split.length > 2) {
for(int i = 0; i < split.length; ++i) {
if(split[i].length() >= 2) {
if(split[i].startsWith(ENCL)) {
split[i] = split[i].substring(1);
}
if(split[i].endsWith(ENCL)) {
split[i] = split[i].substring(0, split[i].length()-1);
}
}
}
}
return split;
})
.filter(s->s.length > 2)
.collect(Collectors.toMap(s -> s[0], s-> Arrays.asList(s[1], s[2])));
// do what you will with ans
return ans.containsKey("AD1");
}
catch(IOException ex) {
// do what you will
}
I am trying to read a .txt file that is not a fixed length and convert it to a certain fixed length. I tried using an array in the while loop for each line that is read to be split() but it kept giving me weird formats, so I took it out! I wanted the institution to be formatted for 40 char lengths, v_25 - sub variables to be a fixed length of 3, and the enrollment variable to be set at 4! Please help!
import java.io.*;
public class FileData {
public static void main (String[] args) {
File file = new File("test.txt");
StringBuffer contents = new StringBuffer();
BufferedReader reader = null;
// int counter = 0;
String institution = null;
String V_25 = null;
String V_75 = null;
String M_25 = null;
String M_75 = null;
String Submit = null;
String Enrollment = null;
try {
reader = new BufferedReader(new FileReader("/Users/GANGSTATOP/Documents/workspace/DBTruncate/src/input.txt"));
String text = null;
// repeat until all lines is read
while ((text = reader.readLine()) != null) {
contents.append(text.replaceAll(",", " ")).append("\nblank\n");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
// show file contents here
System.out.println(contents.toString());
}
}
Originally reading the file:
Adelphi University,500,600,510,620,715,7610
Alabama State University,380,470,380,480,272,5519
How I am trying to make it look like:
(institution) (v_25) (v_75) (m_25) (m_75) (sub) (enroll)
Adelphi University 500 600 510 620 715 7610
blank
Alabama State University 380 470 380 480 272 5519
blank
Here is my suggestion:
BufferedReader reader = null;
List<String> list = new ArrayList<>();
try {
reader = new BufferedReader(new FileReader("input.txt"));
String temp;
while ((temp= reader.readLine()) != null) {
list.add(temp);
}
}
catch (FileNotFoundException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
finally {
try { if (reader != null) { reader.close(); } }
catch (IOException e) { e.printStackTrace(); }
}
System.out.println(String.format("%12s%12s%12s%12s%12s%12s\n\n",
"v_25", "v_72", "m_25", "m_75", "Sub", "Enroll"));
for(int i= 0;i < list.size();i++){
String temp2[] = list.split(",");
if(temp2.length == 6){
System.out.println(String.format("%12s%12s%12s%12s%12s%12s\n\n", temp2[0], temp2[1],temp2[2],temp2[3],temp2[4],temp2[5]);
}
else{
System.out.println("Error");
}
}
That would be my first draft for an answer.
In my opinion you should use an Array and by array I mean a java.util.ArrayList or java.util.List interface, for example:
List<String> list = new ArrayList<>();
A List can easily be added to and grow (among many other things) without the need to initialize it to a specific size as you would with let's say a String[] Array. Since we don't know how many lines of data may be contained within the data file (input.txt) use of the List Interface is a really good way to go, for example:
Required Imports:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
Code to carry out the task:
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("/Users/GANGSTATOP/Documents/workspace/DBTruncate/src/input.txt"));
String text;
List<String> list = new ArrayList<>(); // To hold file data
int longestLength = 0; // Longest University name length
while ((text = reader.readLine()) != null) {
// Add text line to our list array
list.add(text);
// Get the longest length of University names
// for display purposes later on.
if (!text.isEmpty()) {
if (longestLength < text.indexOf(",")) { longestLength = text.indexOf(","); }
}
}
// Sort the List
Collections.sort(list);
// Create & display the Header Line...
String sv = "Institution";
while (sv.length() < longestLength) { sv+= " "; }
sv+= " v_25 v_75 m_25 m_75 Sub Enroll";
System.out.println(sv);
// Create & display the Header Underline...
String ul = "=";
while (ul.length() < (sv.length())) { ul+= "="; }
System.out.println(ul + "\n");
// Iterate through & display the Data...
for (int i = 0; i < list.size(); i++) {
// Pull out the University name from List
// element and place into variable un
String un = list.get(i).substring(0, list.get(i).indexOf(","));
// Right Pad un with spaces to match longest
// University name. This is so everthing will
// tab across console window properly.
while (un.length() < longestLength) { un+= " "; }
// Pull out the university data and convert the
// comma delimiters to tabs then place a newline
// tag at end of line so as to display a blank one.
String data = list.get(i).substring(list.get(i).indexOf(",")+1).replace(",", "\t") + "\n";
//Display the acquired data...
System.out.println(un + "\t" + data);
}
}
catch (FileNotFoundException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
finally {
try { if (reader != null) { reader.close(); } }
catch (IOException e) { e.printStackTrace(); }
}
Once all the file data is contained within the List, hardware access is no longer required and all the data within the List can be easily retrieved, sorted, and manipulated as you see fit unless of course if the data file is quite large and you want to work in Data Chunks.
Here's my solution to your problem. Maybe this is what you've been searching for.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
public class FileData {
public static void main (String[] args) {
FileData fileData = new FileData();
String file = "C:\\Development\\sandbox\\test.txt";
StringBuffer contents = new StringBuffer();
String headline = "(Institution)\t\t\t\t\t(V_25)\t(V_75)\t(M_25)\t(M_75)\t(sub)\t(enrol)\n";
// insert the headline
contents.append(headline);
// read the file and convert it. At this point you've got a list of maps,
// each map containing the values of 1 line addressed by the belonging key
ArrayList<HashMap<String, String>> fileContent = fileData.readData(file);
// now you're going to assemble your output-table
for(HashMap<String, String> lineContent : fileContent){
// Add the institution, but adjust the string size before
contents.append(fileData.stringSizer(lineContent.get("Institution")));
// Add a tab and the next value
contents.append("\t");
contents.append(lineContent.get("V_25"));
// Add a tab and the next value
contents.append("\t");
contents.append(lineContent.get("V_75"));
// Add a tab and the next value
contents.append("\t");
contents.append(lineContent.get("M_25"));
// Add a tab and the next value
contents.append("\t");
contents.append(lineContent.get("M_75"));
// Add a tab and the next value
contents.append("\t");
contents.append(lineContent.get("Submit"));
// Add a tab and the next value
contents.append("\t");
contents.append(lineContent.get("Enrollment"));
// add a new line the word "blank" and another new line
contents.append("\nblank\n");
}
// That's it. Here's your well formed output string.
System.out.println(contents.toString());
}
private ArrayList<HashMap<String, String>> readData(String fileName){
String inputLine = new String();
String[] lineElements;
ArrayList<HashMap<String, String>> fileContent = new ArrayList<>();
HashMap<String, String> lineContent;
// try with resources
try(BufferedReader LineIn = new BufferedReader(new FileReader(fileName))) {
while ((inputLine = LineIn.readLine()) != null){
// every new line gets its own map
lineContent = new HashMap<>();
// split the current line up by comma
lineElements = inputLine.split(",");
// put each value indexed by its key into the map
lineContent.put("Institution", lineElements[0]);
lineContent.put("V_25", lineElements[1]);
lineContent.put("V_75", lineElements[2]);
lineContent.put("M_25", lineElements[3]);
lineContent.put("M_75", lineElements[4]);
lineContent.put("Submit", lineElements[5]);
lineContent.put("Enrollment", lineElements[6]);
// add the map to your list
fileContent.add(lineContent);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// everything went well. Return the list.
return fileContent;
}
private String stringSizer(String value){
// if value is longer than 40 letters return the trimmed version immediately
if (value.length() > 40) {
return value.substring(0, 40);
}
// if values length is lower than 40 letters, fill in the blanks with spaces
if (value.length() < 40) {
return String.format("%-40s", value);
}
// value is exactly 40 letters long
return value;
}
}
Facing some issues with my lab codes
I've done trouble shooting to find that both there's nothing wrong with my filereader/bufferedreaders, Vehicle method and LinkedList values
I'm found out that I'm having Problems getting the if statement to work
I do not know How do I compare the current linkedlist data extracted from my file.txt using tokenizer to pass into given fields with userinput using if/else ?
Main method
package test6;
// import packages
import java.util.LinkedList;
import java.io.*;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Lab6 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
// Declare variables for reading file
FileReader fr = null;
BufferedReader br = null;
String inFile = "Vehicle_Records.txt";
final String INPUT_PROMPT = "\nPlease enter the search word " + "that you would like to obtain more information on:";
String line;
StringTokenizer tokenizer;
// Declare variables to contain the record fields
String group;
String brand;
String model;
double rate;
// Declare and instantiate a new LinkedList
LinkedList<Vehicle> list = new LinkedList<Vehicle>();
try {
// Instantiate FileReader & BufferedReader objects
fr = new FileReader(inFile);
br = new BufferedReader(fr);
//read a line from the file
line = br.readLine();
// While line is not null
while (line != null) {
// Tokenize the records
tokenizer = new StringTokenizer(line, ",");
group = tokenizer.nextToken();
brand = tokenizer.nextToken();
model = tokenizer.nextToken();
rate = Double.parseDouble(tokenizer.nextToken());
// Create a new Vehicle object of the record
Vehicle newVehicle = new Vehicle(group, brand, model, rate);
System.out.println(newVehicle);
// Add this item object into the LinkedList
list.add(newVehicle);
// Read another line from file
line = br.readLine();
}
// Close BufferedReader
br.close();
}
catch (FileNotFoundException e)
{
System.out.println("The file" + inFile + "was not found");
}
catch (IOException e)
{
System.out.println("Reading error!" + e);
}
finally
{
//Check if FileReader is opened
if (fr != null) {
try {
//close FileReader
fr.close();
} catch (IOException e) {
System.out.println("Error closing file!");
}
}
}
// Print out the input prompt
System.out.println(INPUT_PROMPT);
try
{
// Create readers to read from user input
//FileReader ufr = new FileReader(INPUT_PROMPT);
BufferedReader ubr = new BufferedReader(new InputStreamReader (System.in));
// Read one line from user input
String uline=ubr.readLine();
// Loop through all the records in the LinkedList
for(int i = 0; i< list.size(); i++)
{
// if the record is the same as the input from user
// (Hint: use contains() in String class to check whether
// search word is found in the records
String temp = new String(uline);
if(list.get(i)== uline.contains(temp))
{
//print out the information of the vehicle that match user input
System.out.println(list.get(i));
}
}
}
catch(IOException e)
{
System.out.println(e);
}
catch (Exception e)
{
System.out.println("Input error!" + e);
}
}
}//main
Vehical Class
package lab6;
public class Vehicle {
// Declare all the variables to contain the fields of a record
String group;
String brand;
String model;
double rate;
// Creates a constructor to store all the fields into the variables
public Vehicle(String group, String brand, String model, double rate)
{
this.group=group; this.brand=brand; this.model=model; this.rate=rate;
}
// Create a toString() method to return string in the same delimited
// format as the input record
public String toString()
{
return(group+","+brand+","+model+","+rate);
}
}
Your code is not inside a method , so you are facing a problem.
I assume since your looking through vehicle objects trying to find a match of one its four variables. Your approach is wrong since you're comparing an object with a String.
Instead you could use a Comparable interface inside the Vehicle class where you would simply compare multiple strings.
Edit:
public class Vehicle implements Comparable<String>{
/* This method returns 0 if the search matches
* Else it return a negative or a positive number*/
#Override
public int compareTo(String o) {
int cmp = this.getBrand().compareToIgnoreCase(o);
if(cmp == 0) return cmp;
cmp = this.getGroup().compareToIgnoreCase(o);
if(cmp == 0) return cmp;
cmp = this.getModel().compareToIgnoreCase(o);
if(cmp == 0) return cmp;
/* Edited this part to work with doubles */
try{
cmp = (int)(this.getRate() - Double.parseDouble(o));
}
catch(NumberFormatException e){
return cmp;
}
return cmp;
}
}
And here is how you would loop through it:
for(int i = 0; i< list.size(); i++){
if(list.get(i).compareTo(uline) == 0)
{
System.out.println(list.get(i));
}
}
Hope it help.
PS. I'm also new to this :)
AAAAAAAND I FINALLY FIGURED IT OUT TOGETHER WITH MY OTHER FRIEND
Still, I'd love to thank all of you for extending a hand to help me :')
Shall post the solution to my problem here
//-etc-
// Create readers to read from user input
//FileReader ufr = new FileReader(INPUT_PROMPT);
BufferedReader ubr = new BufferedReader(new InputStreamReader (System.in));
// Read one line from user input
String uline=ubr.readLine();
// Loop through all the records in the LinkedList
for(int i = 0; i< list.size(); i++)
{
// if the record is the same as the input from user
// (Hint: use contains() in String class to check whether
// search word is found in the records
Vehicle vehicle = list.get(i);
if(vehicle.group.contains(uline) ||
vehicle.brand.contains(uline) ||
vehicle.model.contains(uline))
{
//print out the information of the vehicle that match user input
System.out.println(list.get(i));
}
I have a list of Strings in single column. I want to make three columns from these string and then print the ouput to another file. How do I do this?
Here is what I've tried so far:
ArrayList<String> list=new ArrayList<String>();
File file = new File("f://file.txt");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
My input data:
City
Gsk
Relocation
sripallu
here
jrajesh
gurgaon
unitech
StatisticsThreads
WizOty
LTDParsvnathK
Quotesby
newest
PMaashuktr
My expected output:
City Gsk Relocation
sripallu here jrajesh
gurgaon unitech StatisticsThreads
WizOty LTDParsvnathK Quotesby
newest PMaashuktr Loans
.
.
.
.
.
.
.
You can structured your requirement in class like Output and make a list of Output.
public class Output{
private String str1;
private String str2;
private String str3;
<geter & setter method>
}
...
ArrayList<Output> list=new ArrayList<Output>();
int i=-1; Output op =null;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();i = ++i%3;
if(i==0){
op = new Output();
op.setStr1(line);
}else if(i==1)
op.setStr2(line);
else
op.setStr3(line);
}
I took your code and modified it a little:
File file = new File("f://file.txt");
try {
Scanner scanner = new Scanner(file);
int itemsOnRow = 0;
while (scanner.hasNextLine())
{
String line = scanner.nextLine();
System.out.print (line + " ");
itemsOnRow++;
if (itemsOnRow == 3)
{
itemsOnRow = 0;
System.out.println ();
}
}
scanner.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
You should actually try to implement it next time. If you fail but post the code that you wrote, then it's easier for the people here to help you.
any way easier to do this??
i'm trying to import a file which is four lines:
name
phone
mobile
address
I'm using:
public void importContacts() {
try {
BufferedReader infoReader = new BufferedReader(new FileReader(
"../files/example.txt"));
int i = 0;
String loadContacts;
while ((loadContacts = infoReader.readLine()) != null) {
temp.add(loadContacts);
i++;
}
int a = 0;
int b = 0;
for (a = 0, b = 0; a < temp.size(); a++, b++) {
if (b == 4) {
b = 0;
}
if (b == 0) {
Name.add(temp.get(a));
}
if (b == 1) {
Phone.add(temp.get(a));
}
if (b == 2) {
Mobile.add(temp.get(a));
}
if (b == 3) {
Address.add(temp.get(a));
}
}
}
catch (IOException ioe) {
JOptionPane.showMessageDialog(null, ioe.getMessage());
}
txtName.setText(Name.get(index));
txtPhone.setText(Phone.get(index));
txtMobile.setText(Mobile.get(index));
txtAddress.setText(Address.get(index));
}
is their an easier way? looks long winded!
You can use the Scanner Class.
Scanner s = new Scanner(new File("input.txt"));
name = s.nextLine();
phone = s.nextLine();
mobile = s.nextLine();
address = s.nextLine();
Apache Fileutils readFileToString() or readLines() makes the code more clean.
import org.apache.commons.io.FileUtils;
...
File file = new File("foobar.txt");
try
{
List<String> data = FileUtils.readLines(file);
// Iterate the result to print each line of the file.
Iterator<String> iter = data.iterator();
while(iter.hasNext()) {
Name.add(iter.next());
if (iter.hasNext()) {
Phone.add(iter.next());
}
if (iter.hasNext()) {
Mobile.add(iter.next());
}
if (iter.hasNext()) {
Address.add(iter.next());
}
}
} catch (IOException e)
{
e.printStackTrace();
}
You could even make it a bit shorter by using a construction like
if (iter.hasNext()) Phone.add(iter.next());
but personally I feel that discarding braces makes code more error-prone. You could put it on one line, though.
Create a data object representing your set of data. With the new object, take in a string and parse it locally in the new object.
Driver Class:
readInFromFile
EntityClass
EntityClass(String) < calls the parse method
get[data elements]
parseFromString(String info) <- this is responsible for all of your reading
The "readFromFile" method will turn into:
....
while ((String line= reader.readLine) != null) {
list.add(new Entity(line));
}
BufferedReader infoReader = new BufferedReader(new FileReader("../files/example.txt"));
String loadContacts;
List<People> list = new ArrayList<People>();
while ((loadContacts = infoReader.readLine()) != null) {
String[] singleContact = loadContacts.split(REGEXP_FOR_SPLIT_VALUES);
People p = new People();
p.setName(singleContact[0]);
p.setPhone(singleContact[1]);
p.setMobile(singleContact[2]);
p.setAddress(singleContact[3]);
list.add(p);
}
How about this?
while(infoReader.hasNext()) {
Name.add(infoReader.readLine());
Phone.add(infoReader.readLine());
Mobile.add(infoReader.readLine());
Address.add(infoReader.readLine());
}
although I'd prefer changing the Name, Phone etc classes to be one class representing one contact.
Here's how I would do it, using the new Scanner class to read easily and take care of IOExceptions, using the ClassLoader to find the file, and using a simple #Data class to store the data.
public void importContacts() {
Scanner scanner = new Scanner(ClassLoader.getSystemClassLoader().getResourceAsStream("example.txt"));
List<Contact> list = Lists.newArrayList();
while(scanner.hasNext()) {
list.add(new Contact(
scanner.nextLine(),
scanner.nextLine(),
scanner.nextLine(),
scanner.nextLine()
));
}
Contact c = list.get(index);
txtName.setText(c.getName());
txtAddress.setText(c.getAddress());
txtPhone.setText(c.getPhone());
txtMobile.setText(c.getMobile());
}
private static #Data class Contact {
private final String name, phone, mobile, address;
}
If the file will only ever contain one contact and you have control over the format of the source text file you could reformat it like a properties file:
name=value
Then you'd read it in as a properties file (see ResourceBundle), which ends up being simple:
Mobile.add(properties.getProperty("mobile"))
Why not just:
public String readLine(BufferedReader pReader) {
try {
return pReader.readLine();
} catch(IOException IOE) {
/* Not a very good practice but let say "We don't care!" */
// Return null if the line is not there (like there was no 4 lines in the file)
return null;
}
}
public void importContacts() {
try {
BufferedReader infoReader = new BufferedReader(new FileReader("../files/example.txt"));
txtName .setText(readLine(infoReader));
txtPhone .setText(readLine(infoReader));
txtMobile .setText(readLine(infoReader));
txtAddress.setText(readLine(infoReader));
} catch (IOException ioe) {
JOptionPane.showMessageDialog(null, ioe.getMessage());
}
}
Hope this helps.