Cant read back data from csv file into arrays - java

So i have this code and i'm having trouble retrieving data from my csv file and putting them into an array.
This is what i have on my CSV file
D001,55,Lab,Butch
D002,22,Husky,Ben
D003,12,Maltese,John
D004,34,GermanSheperd,James
D005,76,Rot,Smith
public static void CSVInputFile() throws IOException {
FileReader inFileReader;
BufferedReader in;
String inStr;
File myFile;
String dogID;
int size;
String breed;
String name;
myFile = new File("DogFile.csv");
inFileReader = new FileReader(myFile);
in = new BufferedReader(inFileReader);
inStr = in.readLine();
Dog[] NewReadDog = new Dog[5];
int i = 0;
while (inStr != null) {
StringTokenizer dogTok = new StringTokenizer(inStr, ",");
while (dogTok.hasMoreTokens()) {
dogID = dogTok.nextToken();
size = new Integer(dogTok.nextToken());
breed = dogTok.nextToken();
name = dogTok.nextToken();
NewReadDog[i] = new Dog(dogID, size, breed, name);
i++;
System.out.println("dog " + i + " is stored");
}
}
System.out.println("\nOutput Dogs from CSV FILE: ");
for (int count = 0; count < NewReadDog.length; count++) {
System.out.println(NewReadDog[count]);
}
in.close();
}
I'm just starting to learn coding so please bear with me.
thanks

You have to read the next line when finished tokenizing the current one:
while (inStr != null) {
StringTokenizer dogTok = new StringTokenizer(inStr, ",");
while (dogTok.hasMoreTokens()) {
[...]
}
System.out.println("dog " + i + " is stored");
inStr = in.readLine();
i++; //replaced here
}

Related

Java Program Add double Quote in all the line

I'm writing a simple program that take a csv file and produce a csv with a new column. My problem is: the program quote the old columns and all the columns.
Below my code
public class CSVmodifier {
public static void modify(String Path,String Escape) throws IOException {
int i=0;
String filename = new File(Path).getName().toString();
//setName(string) modify the original filename
String fileoutname = setName(filename);
File file= new File(fileoutname);
try {
FileWriter out = new FileWriter(file);
Reader reader =
Files.newBufferedReader(Paths.get(Path));
CSVReader csvReader = new CSVReader(reader);
CSVWriter csvWriter = new CSVWriter(out);
String[] nextRecord;
while ((nextRecord = csvReader.readNext()) != null) {
int dimension = nextRecord.length;
String[] newline = new String[dimension+1];
int y = 0;
//formatNumber create a string number with 9
//zero in the front-> 1 > "000000001"
newline[0]=formatNumber(i+1);
while(y<dimension) {
newline[y+1] = nextRecord[y];
y++;
}
i+=1;
csvWriter.writeNext(newline);
}
csvWriter.close();
} finally {
}
}
public static String formatNumber(int i) {
String formatted = String.format("%09d", i);
return formatted;
}
}
my sample is :
"John","Doe","120 jefferson st.","Riverside", "NJ", "08075"
the wrong output is :
"000000001","""John""",""Doe"",""120 jefferson st."",""Riverside"", ""NJ"", ""08075"""
I cannot upload the file, but i'll show you a sample file (input line) that give the same problem:
'1231';'02512710795';'+142142';'2019/12/12';'statale';'blablabla';'iradsasad';'-123131';'+414214141';
'003';'08206810965';'+000000001492106';'2019/06/23';'Scuola statale elemetare';'Ola!'
There Output line:
'000000001';"'1231';'02512710795';'+142142';'2019/12/12';'statale';'blablabla';'iradsasad';'-123131';'+414214141'; "
'000000002';"'003';'08206810965';'+000000001492106';'2019/06/23';'Scuola statale'; "
I assume your CSVWriter class is com.opencsv.CSVWriter.
You are using csvWriter.writeNext(String[]), which is a shortcut for writeNext(nextLine, true); (JavaDoc).
The second parameter, which is always true in this case, is applyQuotesToAll:
True if all values are to be quoted. False applies quotes only to values which contain the separator, escape, quote, or new line characters.
So all you need to do, is changing this line:
csvWriter.writeNext(newline)
to this:
csvWriter.writeNext(newline, false);
This is working for me, check and let me know. Just change the logic in while block it replaces multiple double quotes to a single quote.
public class CSVmodifier {
public static void modify(String Path, String Escape) throws IOException {
int i = 0;
String filename = new File(Path).getName().toString();
//setName(string) modify the original filename
String fileoutname = setName(filename);
File file = new File(fileoutname);
try {
FileWriter out = new FileWriter(file);
Reader reader
= Files.newBufferedReader(Paths.get(Path));
CSVReader csvReader = new CSVReader(reader);
CSVWriter csvWriter = new CSVWriter(out);
String[] nextRecord;
while ((nextRecord = csvReader.readNext()) != null) {
int dimension = nextRecord.length;
String[] newline = new String[dimension + 1];
int y = 0;
//formatNumber create a string number with 9
//zero in the front-> 1 > "000000001"
newline[0] = formatNumber(i + 1);
while (y < dimension) {
newline[y + 1] = nextRecord[y].replace("\"\"", "\"");
if (newline[y + 1].startsWith("\"") && newline[y + 1].endsWith("\"")) {
newline[y + 1] = newline[y + 1].substring(1, newline[y + 1].length() - 1);
}
y++;
}
i += 1;
csvWriter.writeNext(newline);
}
csvWriter.close();
} finally {
}
}
public static String formatNumber(int i) {
String formatted = String.format("%09d", i);
return formatted;
}
}

Search for multiline String in a text file

I have a text file from which i am trying to search for a String which has multiple lines. A single string i am able to search but i need multi line string to be searched.
I have tried to search for single line which is working fine.
public static void main(String[] args) throws IOException
{
File f1=new File("D:\\Test\\test.txt");
String[] words=null;
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
String s;
String input="line one";
// here i want to search for multilines as single string like
// String input ="line one"+
// "line two";
int count=0;
while((s=br.readLine())!=null)
{
words=s.split("\n");
for (String word : words)
{
if (word.equals(input))
{
count++;
}
}
}
if(count!=0)
{
System.out.println("The given String "+input+ " is present for "+count+ " times ");
}
else
{
System.out.println("The given word is not present in the file");
}
fr.close();
}
And below are the file contents.
line one
line two
line three
line four
Use the StringBuilder for that, read every line from file and append them to StringBuilder with lineSeparator
StringBuilder lineInFile = new StringBuilder();
while((s=br.readLine()) != null){
lineInFile.append(s).append(System.lineSeparator());
}
Now check the searchString in lineInFile by using contains
StringBuilder searchString = new StringBuilder();
builder1.append("line one");
builder1.append(System.lineSeparator());
builder1.append("line two");
System.out.println(lineInFile.toString().contains(searchString));
More complicated solution from default C (code is based on code from book «The C programming language» )
final String searchFor = "Ich reiß der Puppe den Kopf ab\n" +
"Ja, ich reiß' ich der Puppe den Kopf ab";
int found = 0;
try {
String fileContent = new String(Files.readAllBytes(
new File("puppe-text").toPath()
));
int i, j, k;
for (i = 0; i < fileContent.length(); i++) {
for (k = i, j = 0; (fileContent.charAt(k++) == searchFor.charAt(j++)) && (j < searchFor.length());) {
// nothig
}
if (j == searchFor.length()) {
++found;
}
}
} catch (IOException ignore) {}
System.out.println(found);
Why don't you just normalize all the lines in the file to one string variable and then just count the number of occurrences of the input in the file. I have used Regex to count the occurrences but can be done in any custom way you find suitable.
public static void main(String[] args) throws IOException
{
File f1=new File("test.txt");
String[] words=null;
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
String s;
String input="line one line two";
// here i want to search for multilines as single string like
// String input ="line one"+
// "line two";
int count=0;
String fileStr = "";
while((s=br.readLine())!=null)
{
// Normalizing the whole file to be stored in one single variable
fileStr += s + " ";
}
// Now count the occurences
Pattern p = Pattern.compile(input);
Matcher m = p.matcher(fileStr);
while (m.find()) {
count++;
}
System.out.println(count);
fr.close();
}
Use StringBuilder class for efficient string concatenation.
Try with Scanner.findWithinHorizon()
String pathToFile = "/home/user/lines.txt";
String s1 = "line two";
String s2 = "line three";
String pattern = String.join(System.lineSeparator(), s1, s2);
int count = 0;
try (Scanner scanner = new Scanner(new FileInputStream(pathToFile))) {
while (scanner.hasNext()) {
String withinHorizon = scanner.findWithinHorizon(pattern, pattern.length());
if (withinHorizon != null) {
count++;
} else {
scanner.nextLine();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println(count);
Try This,
public static void main(String[] args) throws IOException {
File f1 = new File("./src/test/test.txt");
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
String input = "line one";
int count = 0;
String line;
while ((line = br.readLine()) != null) {
if (line.contains(input)) {
count++;
}
}
if (count != 0) {
System.out.println("The given String " + input + " is present for " + count + " times ");
} else {
System.out.println("The given word is not present in the file");
}
fr.close();
}

Reading text file variables and updated assigned values

I have a text file which has text as follows:
emVersion = "1.32.4.0";
ecdbVersion = "1.8.9.6";
ReleaseVersion = "2.3.2.0";
I want to update the version number by taking the input from a user if user enter the new value for emVersion as 1.32.5.0 then
emVersion in text file will be updated as emVersion = "1.32.5.0";
All this I have to do using java code. What I have done till now is reading text file line by line then in that searching the word emVersion if found the broken line into words and then replace the token 1.32.4.0 but it is not working because spaces are unequal in the file.
Code what i have written is :
public class UpdateVariable {
public static void main(String s[]){
String replace = "1.5.6";
String UIreplace = "\""+replace+"\"";
File file =new File("C:\\Users\\310256803\\Downloads\\setup.rul");
Scanner in = null;
try {
in = new Scanner(file);
while(in.hasNext())
{
String line=in.nextLine();
if(line.contains("svEPDBVersion"))
{
String [] tokens = line.split("\\s+");
String var_1 = tokens[0];
String var_2 = tokens[1];
String var_3 = tokens[2];
String var_4 = tokens[3];
String OldVersion = var_3;
String NewVersion = UIreplace;
try{
String content = IOUtils.toString(new FileInputStream(file), StandardCharsets.UTF_8);
content = content.replaceAll(OldVersion, NewVersion);
IOUtils.write(content, new FileOutputStream(file), StandardCharsets.UTF_8);
} catch (IOException e) {
}
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//---this code changes each version's values but the is a option to keep the old value.
Scanner in = new Scanner(System.in);
File file = new File("versions.txt");
ArrayList<String> data = new ArrayList<>();
String[] arr =
{
"emVersion", "ecdbVersion", "releaseVersion"
};
String line = "";
String userInput = "";
try (BufferedReader br = new BufferedReader(new FileReader(file));)
{
while ((line = br.readLine()) != null)
{
data.add(line);
}
for (int i = 0; i < arr.length; i++)
{
System.out.println("Please enter new " + arr[i] + " number or (s) to keep the old value.");
userInput = in.nextLine();
line = data.get(i);
String version = line.substring(0, line.indexOf(" "));
if (arr[i].equalsIgnoreCase(version))
{
arr[i] = line.replace(line.subSequence(line.indexOf("= "), line.indexOf(";")), "= \"" + userInput + "\"");
}
if (userInput.equalsIgnoreCase("s"))
{
arr[i] = line;
}
}
PrintWriter printWriter = new PrintWriter(new FileWriter(file, false));
printWriter.println(arr[0]);
printWriter.println(arr[1]);
printWriter.println(arr[2]);
printWriter.close();
}
catch (Exception e)
{
System.out.println("Exception: " + e.getMessage());
}
Use regular expression eg:- line.trim().split("\s*=\s*"); . If it does not work please let me know , i will provide you complete solution.

Java Array save input to txt file

I have created this code to save students info to txt file but it only saves the name. I can't find what's wrong with this any ideas? I'm not getting any errors programma runs just fine expect some error handling and other things i have to add.
Main class
public class Main {
public static void main(String[] args) throws IOException {
File fileName = new File("Students.txt");
ArrayList Students = new ArrayList();
String studentName = " ";
String studentSName = " ";
String idstudent = " ";
String course = " ";
while (!studentName.isEmpty()) {
studentName = JOptionPane.showInputDialog("Student's Name: ");
studentSName = JOptionPane.showInputDialog("Student's Surname: ");
idstudent = JOptionPane.showInputDialog("Student's IDnumber: ");
course = JOptionPane.showInputDialog("Student's Course: ");
if (!studentName.isEmpty()) {
Students.add(studentName);
}
}
try {
FileWriter fw = new FileWriter(fileName);
Writer output = new BufferedWriter(fw);
int sz = Students.size();
for (int i = 0; i < sz; i++) {
output.write(Students.get(i).toString() + "\n");
}
output.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "file not found");
}
}
}
2nd class:
public class filereading {
public static void main(String[] args) {
String FileName = "students.txt";
String line;
ArrayList Students = new ArrayList();
try {
BufferedReader input = new BufferedReader(new FileReader(FileName));
if (!input.ready()) {
throw new IOException();
}
while ((line = input.readLine()) != null) {
Students.add(line);
}
input.close();
} catch (IOException e) {
System.out.println(e);
}
int sz = Students.size();
for (int i = 0; i < sz; i++) {
System.out.println(Students.get(i).toString());
}
}
}
Because you add only name to List
if (!studentName.isEmpty()) Students.add(studentName);
You have to add something like this:
Students.add(String.format("%s %s, id: %s, course: %s", studentName, studentSName, idstudent, course));

Java Code check fields in duplicate, when value change start again

I want to write small java program to read data file first field and add seqcution number
Input file:
robert,190 vikign,...
robert,2401 windy,...
robert,1555 oakbrook,...
michell,2524 sprint,...
michell,1245 oakbrrok,...
xyz,2455 xyz drive,....
Output file should be:
robert,190 vikign,...,0
robert,2401 windy,...,1
robert,1555 oakbrook,...,2
michell,2524 sprint,...,0
michell,1245 oakbrrok,...,1
xyz,2455 xyz drive,....,0
Check first field when value change sequction number start back to 0 otherwise add sequction number by 1
here is my code:
public static void createseq(String str) {
try {
BufferedReader br = null;
BufferedWriter bfAllBWP = null;
File folderall = new File("Sort_Data_File_Out");
File[] BFFileall = folderall.listFiles();
for (File file : BFFileall) {
br = new BufferedReader(new FileReader(file));
String bwp = "FinalDataFileOut\\" + str;
bfAllBWP = new BufferedWriter(new FileWriter(bwp));
String line;
line = br.readLine();
String[] actionID = line.split("\\|");
String fullname = actionID[0].trim();
int seq = 0;
String fullnameb;
while ((line = br.readLine()) != null) {
actionID = line.split("\\|");
fullnameb = actionID[0].trim();
if(fullname.equals(fullnameb)) {
seq++;
}
else {
System.out.println(line + "======" + seq + "\n");
seq = 0;
fullname = fullnameb;
}
System.out.println("dshgfsdj "+line + "======" + seq + "\n");
}
}
}
catch(Exception letterproof) {
letterproof.printStackTrace();
}
}
The below code will fix the issue.I have updated the code if you face any pblm plz let me know :
Input :
robert,190 vikign,...
robert,2401 windy,...
robert,1555 oakbrook,...
michell,2524 sprint,...
michell,1245 oakbrrok,...
xyz,2455 xyz drive,....
Code :
public static void createseq() {
try {
File file = new File("d:\\words.txt"); //Hardcoded file for testing locally
BufferedReader br = new BufferedReader(new FileReader(file));
HashMap<String,Integer> counter = new HashMap<String, Integer>();
String line;
while((line = br.readLine())!= null)
{
String[] actionID = line.split(",");
String firstName = actionID[0];
if(counter.containsKey(firstName))
{
counter.put(firstName, counter.get(firstName) + 1);
}
else
{
counter.put(firstName,0);
}
System.out.println(line+" "+counter.get(firstName));
}
br.close();
} catch(Exception letterproof) {
letterproof.printStackTrace();
}
}
Ouput Come :
robert,190 vikign,... 0
robert,2401 windy,... 1
robert,1555 oakbrook,... 2
michell,2524 sprint,... 0
michell,1245 oakbrrok,... 1
xyz,2455 xyz drive,.... 0

Categories

Resources