Java string comparisions/quotations - java

My problem is the comparision of two objects and the strings that they return (accessed through getters).
Object one parses a csv file for dates and when printed out through exampleObject.getDateTime() returns the string: "2010-03-26-10-54-06.471000"
Object two has its dateTime string set by the user. When I set the dateTime on object two to be the same as objectOne and then do exampleObjectTwo.getDateTime() it returns 2010-03-26-10-54-06.471000
So the main difference is that one string has quotations from parsing the csv (which contains no quotations) and the user set string when returned has no quotations!
If anyone can offer an explanation as to why this is happening I'd be very grateful!
Many thanks!
BufferedReader input = new BufferedReader(new FileReader(file));
try {
String line = null;
while ((line = input.readLine()) != null) {
SearchResult searchResult = new SearchResult();
if (!line.contains("Date")) {
String[] split = line.split(",");
SearchResult.setDateTime(split[0]);
SearchResults.add(SearchResult);
}
}
} finally {
input.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
edit above is the code that was using to parse the csv file. I checked and the csv file does not contain any quotations.
Thanks for the quick and helpful response!

You need to modify/configure the CSV parser to remove the quotes.
If it's a homegrown CSV parser, doing so should suffice to get rid of the surrounding doublequotes:
field = field.replaceAll("^\"|\"$", "");
If it's a 3rd party API, then you need to consult its documentation (or mention the library name here so that one who is willing to do that can lookup the documentation for you).
See also:
How to parse CSV in Java?

check again how do you perform csv parsing.
or remove quotations from string:
String newDate = oldString.replaceAll("\""," ").trim();

Related

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.

How can I read and work on a textual file starting from its path in Java?

I have the following task that have to be implemented in Java.
I have a String that represent the path of a txt file, something like this:
String fileFatturePa = "C:\\Users\\Andrea\\Desktop\\D150316.T1642\\myFile.txt";
This textual file contains some text (that represent XML but this is not important because I do not have to operate on it with something like XPath but I have to do simple substring operation).
So I need to read this textual file (starting from its path) and then I have to do some textual operation.
This file could be very big.
What is the best way to read it stargint from its path?
A good starting point is the official Java documentation by Oracle: Basic I/O.
BufferedReader reader = new BufferedReader(new FileReader(fileFatturePa));
try
{
String line = null;
while ((line = reader.readLine()) != null)
{
***operations(specific to each line of the text file) ***
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
finally
{
reader.close();
}
Simple, you create a new File: File f = new File(path). For raed all the lines, you can use the class Fileutils from Apache Commons IO. And you will have something like: List<String> allLines=Fileutils.readlines(f)

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: read multiple lines into a single string

I'm reading numbers from a txt file using BufferedReader for analysis. The way I'm going about this now is- reading a line using .readline, splitting this string into an array of strings using .split
public InputFile () {
fileIn = null;
//stuff here
fileIn = new FileReader((filename + ".txt"));
buffIn = new BufferedReader(fileIn);
return;
//stuff here
}
public String ReadBigStringIn() {
String line = null;
try { line = buffIn.readLine(); }
catch(IOException e){};
return line;
}
public ProcessMain() {
initComponents();
String[] stringArray;
String line;
try {
InputFile stringIn = new InputFile();
line = stringIn.ReadBigStringIn();
stringArray = line.split("[^0-9.+Ee-]+");
// analysis etc.
}
}
This works fine, but what if the txt file has multiple lines of text? Is there a way to output a single long string, or perhaps another way of doing it? Maybe use while(buffIn.readline != null) {}? Not sure how to implement this.
Ideas appreciated,
thanks.
You are right, a loop would be needed here.
The usual idiom (using only plain Java) is something like this:
public String ReadBigStringIn(BufferedReader buffIn) throws IOException {
StringBuilder everything = new StringBuilder();
String line;
while( (line = buffIn.readLine()) != null) {
everything.append(line);
}
return everything.toString();
}
This removes the line breaks - if you want to retain them, don't use the readLine() method, but simply read into a char[] instead (and append this to your StringBuilder).
Please note that this loop will run until the stream ends (and will block if it doesn't end), so if you need a different condition to finish the loop, implement it in there.
I would strongly advice using library here but since Java 8 you can do this also using streams.
try (InputStreamReader in = new InputStreamReader(System.in);
BufferedReader buffer = new BufferedReader(in)) {
final String fileAsText = buffer.lines().collect(Collectors.joining());
System.out.println(fileAsText);
} catch (Exception e) {
e.printStackTrace();
}
You can notice also that it is pretty effective as joining is using StringBuilder internally.
If you just want to read the entirety of a file into a string, I suggest you use Guava's Files class:
String text = Files.toString("filename.txt", Charsets.UTF_8);
Of course, that's assuming you want to maintain the linebreaks. If you want to remove the linebreaks, you could either load it that way and then use String.replace, or you could use Guava again:
List<String> lines = Files.readLines(new File("filename.txt"), Charsets.UTF_8);
String joined = Joiner.on("").join(lines);
Sounds like you want Apache IO FileUtils
String text = FileUtils.readStringFromFile(new File(filename + ".txt"));
String[] stringArray = text.split("[^0-9.+Ee-]+");
If you create a StringBuilder, then you can append every line to it, and return the String using toString() at the end.
You can replace your ReadBigStringIn() with
public String ReadBigStringIn() {
StringBuilder b = new StringBuilder();
try {
String line = buffIn.readLine();
while (line != null) {
b.append(line);
line = buffIn.readLine();
}
}
catch(IOException e){};
return b.toString();
}
You have a file containing doubles. Looks like you have more than one number per line, and may have multiple lines.
Simplest thing to do is read lines in a while loop.
You could return null from your ReadBigStringIn method when last line is reached and terminate your loop there.
But more normal would be to create and use the reader in one method. Perhaps you could change to a method which reads the file and returns an array or list of doubles.
BTW, could you simply split your strings by whitespace?
Reading a whole file into a single String may suit your particular case, but be aware that it could cause a memory explosion if your file was very large. Streaming approach is generally safer for such i/o.
This creates a long string, every line is seprateted from string " " (one space):
public String ReadBigStringIn() {
StringBuffer line = new StringBuffer();
try {
while(buffIn.ready()) {
line.append(" " + buffIn.readLine());
} catch(IOException e){
e.printStackTrace();
}
return line.toString();
}

how do I extract Name and Value from a line of text while reading from a file using Java?

A file name will be passed in from standard in. I want to open it, read it, and create some information based off the text in the file.
For example, if this is a line in the file:
Hristo 3
... then I want to create a Member() named Hristo with a value of 3. So I want to pull out a String for the name and an int for the value. The name and the value are separated by some unknown number of tabs and spaces which I need to ignore. Could I just read the line, use .trim() to get rid of whitespace, and the last character would be the value?
I have not shown the class Member() for simplicity's sake. This is what I have so far:
public static void main(String[] args) {
int numMembers = 0;
ArrayList<Member> veteranMembers = new ArrayList<Member>();
File file = new File(args[0]);
FileReader fr;
BufferedReader br;
// attempt to open and read file
try {
fr = new FileReader(file);
br = new BufferedReader(fr);
String line;
// read file
while ((line = br.readLine()) != null) {
// extract name and value from line
... ? ...
// create member
// initialize name and value
Member member = new Member();
veteranMembers.add(member);
}
br.close();
} catch (FileNotFoundException e1) {
// Unable to find file.
e1.printStackTrace();
} catch (IOException e) {
// Unable to read line.
e.printStackTrace();
}
}
How would I parse that line of text?
Thanks in advance for your help.
I would use the split function.
You can give it a regular expression as the argument
i.e.
line.split(" |\t");
will return array of the words ( {list[0] = Hristo, list[1] = 3} in your example)
Hope it helps.
Use split("\\s+"), this regex ignore any space, tab, etc from the String.
A more robust way might be to use regular expressions; if you received malformed input (e.g., "Ted One"), parseInt() would throw a NumberFormatException.
import java.util.regex.*;
...
Pattern p = Pattern.compile("^(.*)\\s+(\\d+)$"); // Create a regex Pattern that only matches (text - white space - integer)
Matcher m = p.matcher(line); // Create a Matcher to test the input line
if(m.find()){
// If there's a match, ..
String name = m.group(1); // Set "name" to the first parenthesized group
String value = m.group(2); // Set "value" to the second parenthesized group
}
else{
// Bad Input
}
Looks like a home work. You came really close doing it. Use StringTokenizer to tokenize the line. Then create a new member object and and call setters for both the attributes with tokens as params. If your second attribute is an int use parseInt to convert and assign it.

Categories