importing a text file - java

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.

Related

Parsing CSV file on Java to extract String

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
}

Need help parsing a csv file and gathering the information together

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();
}
}

How to put Output in ArrayList from a file in Local

I am trying to segregate my data into multiple array list, so that I can use them later-on in my code. But I am not able to put my data in array list.
My code is about segregating the data into three array list of different Subjects (Example:Physics,chemistry) as per various filters, which you will find in my code.
Input data file:
1|150|20150328|20150406|Physics|1600|1600|2|68|92
2|152|20150328|20150406|Physics|1600|1500|2|68|89
3|153|20150328|20150406|Physics|1600|1500|2|68|60
4|155|20150328|20150406|Physics|1600|1600|2|68|72
5|161|20150328|20150406|Chemistry|1600|1600|2|68|77
Here's my code:
Public Class filter{
public static void main(String args[])
BufferedReader in= null;
BufferedWriter out= null;
String in_line;
String PrevRollNo= "";
int PrevDate= 0;
ArrayList<transaction> PhysicsList= new ArrayList<transaction>();
ArrayList<transaction> scList= new ArrayList<transaction>();
ArrayList<transaction> Chemistry= new ArrayList<transaction>();
try{
in = new BufferedReader(new FileReader(Path for input file));
File out_file= new File(Path for output file);
if(!out_file.exists())
{
(!out_file.createNewFile();
}
FileWriter fw=new FileWriter(out_file);
out= new BufferedWriter(fw);
while ((in_line=in.readline())!=null)
{
Transaction transact=new Transaction(in_line);
if(transact.RollNo.equals(PrevRollNo))
{
if(transact.subject.equals("Physics")&& transact.Prs_Date= PrevDate
{
PhysicsList.add(transact);
}
else if(transact.subject.equals("Physics")&&transact.wk_date != PrevDate}
Iterator<Transaction> it;
if(!transact.RoomNo.equals("102")&&!transact.lcl_RoomNo.equals("102");
{
it= scList.iterator();
while(it.hasnext())
{
Transaction sc= it.next();
if(sc.lcl_RoomNo.equals(transact.RoomNo) && sc.l1 equals(tansact.l1) && sc.l2 equals(transact.l2)
if(sc.marks==transact.marks)
{
transact.srsfound= true;
}
else
{
System.out.print.ln( "not found");
}
scList.remove(sc))
out.write(in_line);
break;
}}}}
Static Class Transaction
{
Public String RollNo, Subject, RoomNo, lcl_RoomNo, l1, l2;
Public int wk_date, prs_date;
Public double marks , amt;
Public boolean srcfound, tgtfound;
Public Transaction(String in_line)
{
String [] SplitData= in_line.split("\\|");
RollNo = SplitData[1];
Subject = SplitData[4]
RoomNo = SplitData[5];
lcl_RoomNo = SplitData[6];
l1 = SplitData[7];
l2 = SplitData[8];
wk_date = SplitData[3];
prs_date = SplitData[2];
marks = Double.parsedouble(SplitData[9]);
amt = Double.parsedouble(SplitData[]);
srcfound = false;
tgtfound = false;
}
Kindly help with your expertise.
Use Java 8 NIO and Streams. It will ease the job.
Files.lines(Paths.get("fileName.txt")).map(line -> {
String[] tokens = line.split("|");
//tokens contains individual elements of each line. Add your grouping logic on tokens array
}
I agree with the other answer in some ways. NIO should be used, it makes it a lot easier. However, I would avoid streams and instead use the readAllLines method like so:
try{
List<String> filecontents = new String(Files.readAllLines(file.toPath()); //file is the object to read from.
for(int i = 0; i < filecontents.size(); i++){
String line = lines.get(i);
//New code starts here
if(!line.contains("|") continue; //Ignore that line
//New code ends here
String[] array = line.split("|");
ArrayList<String> list = new ArrayList<String>();
for(int a = 0; a < array.length; a++){
String part = array[a];
list.add(part);
}
Transaction t = new Transaction(line);
if(line.contains("Physics") PlysicsList.add(t);
else if(line.contains("Chemistry") Chemistry.add(t);
else{ //Do nothing}
}
}catch(IOException e){
e.printStackTrace();
}
EDIT: I added a check in there. The reason the first and last lines may not be working is if the lines that are being parsed are not being parsed properly. See if this fixes your issue

Getting values from LinkedList according to user input

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));
}

More Effective way of picking a part a String from JTextPane?

It's not that my code doesn't work, but I am doubting whether it's very efficient or not. My theory is, that it isn't xD
I have a JTextPane where I have to take the text in it (Making a new line every time the JTextPane got a new line basically), and put it into a .txt file. As I said everything works but I am doubting the implementation of it.
This is the part I am doubting:
public void printLog() {
String s = logTextArea.getText();
ArrayList<String> log = new ArrayList<>();
StringBuilder sb = new StringBuilder();
for(int i = 0; i < s.length(); i++) {
if(s.charAt(i) != '\n') {
sb.append(s.charAt(i));
} else {
log.add(sb.toString());
sb.delete(0, sb.length());
}
}
This is the entire thing just for reference:
public void printLog() {
String s = logTextArea.getText();
ArrayList<String> log = new ArrayList<>();
StringBuilder sb = new StringBuilder();
for(int i = 0; i < s.length(); i++) {
if(s.charAt(i) != '\n') {
sb.append(s.charAt(i));
} else {
log.add(sb.toString());
sb.delete(0, sb.length());
}
}
File f = new File("JServer_Log.txt");
BufferedWriter bw = null;
FileWriter fr = null;
try {
if(f.exists()) {
fr = new FileWriter(f,true);
} else {
fr = new FileWriter(f);
}
} catch (IOException e) {
// Nothing to do really.
}
try {
bw = new BufferedWriter(fr);
Iterator<String> itr = log.iterator();
bw.newLine();
while(itr.hasNext()) {
bw.write(itr.next());
bw.newLine();
}
} catch (IOException e) {
// Nothing to do really. We lost the log?
} finally {
try {
bw.close();
} catch(IOException ioe) {
// The program is closing any way.
}
}
}
It seems that you just need to make sure you use the platform's appropriate newline sequence. You can just say s = s.replace("\n", System.getProperty("line.separator")) and then write that whole string directly to file. In fact, the way I see it, this is all the code you need (except maybe for exception handling, up to you):
public void printLog() throws IOException {
final FileWriter w = new FileWriter("JServer_Log.txt", true);
try {
w.write(logTextArea.getText().replace("\n",
System.getProperty("line.separator")));
} finally { w.close(); }
}
For information, the first code can be replaced by:
List<String> log = Arrays.asList(logTextArea.getText().split("\n"));
but other answers give you a way to replace the whole method.
Why bothering, to use JTextComponents.write(Writer out) throws IOExceptionwrite() this is pretty accepting newline, tabs, e.i. that came from Native OS
use split:
String[] log = s.split("\n");

Categories

Resources