reading in csv file and storing in arrays - java

the practice question i got says that i need to
create a java code that reads in csv file with name and height.
to read a file you must get a file name from user as string.
then you must store contents of file into two arrays one for name (string) and height(real number).
You should read the file at least twice, once to check how many students are in the file (so you know how many students you need to store) and a couple more times to actually read the file (to get the names and height).
then prompt the user for name you want height of. it should output the height for userinput.
example csv file is
chris,180
jess,161
james, 174
its not much but this is all i could come up with i have no idea how to store name and height separately and use that array to output the results. and would i need to use split somewhere in the code? i remember learning it but dont know if its used in this situation
import.java.util.*;
private class StudentNameHeight
private void main (string [] args)
{
String filename;
Scanner sc = new scanner(system.in);
System.out.println("enter file name")
filename = sc.nextline();
readFile (filename);
}
private void readFile (String filename)
{
FileInputStream fileStrm = null;
InputStreamReader rdr;
BufferedReader bufRdr;
try
{
fileStrm = new FileInputStream(filename);
rdr = new InputStreamReader(fileStrm);
bufRdr = new BufferedReader(rdr);
// ?
catch (IOException e)
{
if (fileStrm != null)
{
try {fileStrm.close(); } catch (IOException e2){}
}
System.out.println("error in processing" + e.getMessage());
}
}
im new to java so, any small tip or help would be great
thanks

You code looks messy. As far as I understand from your question, you are willing to read a CSV file containing two entities, one is name and another is height and store these two entities in two different data structures. I'm teaching you a simple way to accomplish this in below code snippet.
public void processCSVFile(String filePath){
try(BufferedReader fileReader = new BufferedReader(new FileReader(new File(filePath)))){
//Create two lists to hold name and height.
List<String> nameList = new ArrayList<>();
List<Integer> heightList = new ArrayList<>();
String eachLine = "";
/*
* Read until you hit end of file.
*/
while((eachLine = fileReader.readLine()) != null){
/*
* As it is CSV file, split each line at ","
*/
String[] nameAndHeightPair = eachLine.split(",");
/*
* Add each item into respective lists.
*/
nameList.add(nameAndHeightPair[0]);
heightList.add(Integer.parseInt(nameAndHeightPair[1]));
}
/*
* If you are very specific, you can convert these
* ArrayList to arrays here.
*/
}catch(IOException e1){
e1.printStackTrace();
}
}

Related

Java read input/output print duplicate string to file

Hi I am working on this problem, Suppose a library is processing an input file containing the titles of books in order to identify duplicates. Write a program that reads all of the titles from an input file called bookTitles.inp and writes them to an output file called duplicateTitles.out. When complete, the output file should contain all titles that are duplicated in the input file. Note that the duplicate titles should be written once, even though the input file may
contain same titles multiple times. If there are not duplicate titles in the input file, the output file should be empty. Create the input file using Notepad or another text editor, with one title per line. Make sure you have a number of duplicates, including some with three or more copies.
So far I have this but It is printing the duplicates more than once if I change the order of the input file. Thanks.
import java.io.*;
public class Library
{
public static void main(String[] args) throws IOException
{
String line3="";
boolean dup = false;
// PrintWriter object for output.txt
PrintWriter pw = new PrintWriter("C:\\Users\\Ilyas\\Desktop\\tempBookTitles.txt");
PrintWriter pw2 = new PrintWriter("C:\\Users\\Ilyas\\Desktop\\duplicateTitles.txt");
// BufferedReader object for input.txt
BufferedReader br1 = new BufferedReader(new
FileReader("C:\\Users\\Ilyas\\Desktop\\bookTitles.txt")); //read input file
String line1 = br1.readLine();
// loop for each line of input.txt
while(line1 != null)
{
boolean flag = false;
// BufferedReader object for output.txt
BufferedReader br2 = new BufferedReader(new
FileReader("C:\\Users\\Ilyas\\Desktop\\tempBookTitles.txt"));
BufferedReader br3 = new BufferedReader(new
FileReader("C:\\Users\\Ilyas\\Desktop\\duplicateTitles.txt")); //try
String line2 = br2.readLine();
// loop for each line of output.txt
while(line2 != null)
{
if(line1.equals(line2))
{
line3 = br3.readLine();
flag = true;
if(line1.equals(line3))
{
line1 = null;
}
else
{
pw2.println(line1);
pw2.flush();
//break;
}
}
}
line2 = br2.readLine();
}
// if flag = false
// write line of input.txt to output.txt
if(flag==false)
{
pw.println(line1); //print to temp file, delete temp file at end
pw.flush();
}
line1 = br1.readLine();
}
br1.close();
pw.close();
pw2.close();
System.out.println("File operation performed successfully");
}
}
You should try to make the program readable, and also make it smaller by breaking into chunks of methods.
See my suggestion below.
private List<String> getAllTitles(String filepath){
List<String> titles = new ArrayList<>();
// read the file,
// for each of the titles, insert into the list
return titles;
}
private Set<String> getDuplicates(List<String> titles){
Set<String> alreadyReadSet = new HashSet<>();
Set<String> duplicateSet = new HashSet<>();
for (String title : titles) {
if(/*alreadyReadSet contains the title*/){
// put title into duplicateList
}
// put the title into alreadyReadSet
}
return duplicateSet;
}
private void printDuplicateList(Collection<String> duplicateList){
// print to a file
}
To solve it without maps, you can use method contains, instead of writing directly to output file, create a output variable String, and change
{
pw2.println(line1);
pw2.flush();
}
for
if (!output.contains(line1+"\n"))
output=output + line1+"\n"
and after the loop print output to the file
So I am sure you have solved your problem by now, but in case anyone else comes across this thread looking for advice...
I encountered this same problem in my schoolwork recently and it drove me nuts trying to solve it with the tools we had learned so far in the course (which did not include maps or ArrayList). I ended up looking into the documentation for BufferedReader; and using the mark(int readLimit) and reset() methods. I got 100% on the assignment, so I thought I would leave this tip here for others.

Creating Multiple Arrays From a Text File in JAVA

I'm in a low level program design class and am struggling with creating arrays from data given in a text file. The file name is students.txt and it is formatted in this manner:
1234
Joseph
3
4.0 (except it is single spaced)
Where the first number (an integer) is the Student ID, followed by the student name, followed by credit hours, and finished with GPA. This is an example of course and the file contains many records.
In the end I am going to create a record that is organized in sequential order by one of the fields above. What I need help with is creating multiple arrays for each field. I'm thinking it would be very helpful if I could have a student_ID array, name array, credit_hour array, and gpa array.
Here is my best shot and attempt:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package filetoarray;
import java.util.*;
import java.io.*;
/**
*
* #author whitn
*/
public class FileToArray {
/**
* #param args the command line arguments
*/
public static void main(String[] args)throws IOException {
//Here I am establishing my arrays
int[]student_ID;
student_ID = new int[100];
String[]name;
name = new String[100];
int[]credit_hour;
credit_hour = new int[100];
double[]gpa;
gpa = new double[100];
// I am not too sure what FileReader and BufferedReader do but I think
// I am creating a way for the program to read from the file students.txt
FileReader fr = new FileReader ("C:\\Users\\whitn\\Desktop\\students.txt");
BufferedReader snames = new BufferedReader(fr);
//Here I am initializng my variables
String name1 = " "; //called name1 to not confuse it with array 'name'
String next = " ";
int s_ID = 0;
int c_hour = 0;
double gpa1 = 0.0;
//Now I don't really know how to proceed. Do use something like
// student_ID[x] = Integer.parseInt(next)
// name[x] = snames.nextLn();
// credit_hour[x] = snames.nextInt();
// gpa[x] = snames.nextDouble();
//Do I even need the variable initialized above?
}
}
I'm pretty sure if I can figure out how to create an array from the fields provided in the file I can finish the problem. Any help would be greatly appreciated. I am in my first programming class and don't know much, therefore, if I've left out valuable information let me know!
Thank you
You can use readline method of bufferreader to read line by line and that's how you pick one record in the form of string.
Now if are separated by space or comma , you can use string method split which will return you an array of string now by index you can assign values to all your variable by that array of string or you can directly use that array of string
Make a class for reading file content like
import java.io.*;
public class FileReader {
private String fileName, fileContent = null, line;
public FileReader(String f) {
fileName = f;
reader();
}
private void reader() {
try {
fileContent = "";
// FileReader reads text files in the default encoding
Reader fileReader = new java.io.FileReader(fileName);
// Wrapping FileReader in BufferedReader
BufferedReader bufferedReader = new BufferedReader(fileReader);
while ((line = bufferedReader.readLine()) != null) {
fileContent += line;
fileContent += '\n';
}
// Closing the file
bufferedReader.close();
} catch (FileNotFoundException ex) {
System.out.println("Unable to open file '" + fileName + "'");
} catch (IOException ex) {
System.out.println("Error reading file '" + fileName + "'");
}
}
/**
* Get content of file
*
* #return String
*/
public String getFileContent() {
return fileContent;
}
}
Create a class for Student
public class Student {
public String name;
public int id, creditHour;
public double gpa;
// add constructor and setter/getter methods
}
Create a class for starting project with main method. get file content from FileReader class. Define an array of students. Loop over its content and fill your array.

Java -- Need help to enhance the code

I wrote a simple program to read the content from text/log file to html with conditional formatting.
Below is my code.
import java.io.*;
import java.util.*;
class TextToHtmlConversion {
public void readFile(String[] args) {
for (String textfile : args) {
try{
//command line parameter
BufferedReader br = new BufferedReader(new FileReader(textfile));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
Date d = new Date();
String dateWithoutTime = d.toString().substring(0, 10);
String outputfile = new String("Test Report"+dateWithoutTime+".html");
FileWriter filestream = new FileWriter(outputfile,true);
BufferedWriter out = new BufferedWriter(filestream);
out.write("<html>");
out.write("<body>");
out.write("<table width='500'>");
out.write("<tr>");
out.write("<td width='50%'>");
if(strLine.startsWith(" CustomerName is ")){
//System.out.println("value of String split Client is :"+strLine.substring(16));
out.write(strLine.substring(16));
}
out.write("</td>");
out.write("<td width='50%'>");
if(strLine.startsWith(" Logged in users are ")){
if(!strLine.substring(21).isEmpty()){
out.write("<textarea name='myTextBox' cols='5' rows='1' style='background-color:Red'>");
out.write("</textarea>");
}else{
System.out.println("else if block:");
out.write("<textarea name='myTextBox' cols='5' rows='1' style='background-color:Green'>");
out.write("</textarea>");
} //closing else block
//out.write("<br>");
out.write("</td>");
}
out.write("</td>");
out.write("</tr>");
out.write("</table>");
out.write("</body>");
out.write("</html>");
out.close();
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
e.printStackTrace();
}
}
}
public static void main(String args[]) {
TextToHtmlConversion myReader = new TextToHtmlConversion();
String fileArray[] = {"D:/JavaTesting/test.log"};
myReader.readFile(fileArray);
}
}
I was thinking to enhance my program and the confusion is of either i should use Maps or properties file to store search string. I was looking out for a approach to avoid using substring method (using index of a line). Any suggestions are truly appreciated.
From top to bottom:
Don't use wildcard imports.
Don't use the default package
restructure your readFile method in more smaller methods
Use the new Java 7 file API to read files
Try to use a try-block with a resource (your file)
I wouldn't write continuously to a file, write it in the end
Don't catch general Exception
Use a final block to close resources (or the try block mentioned before)
And in general: Don't create HTML by appending strings, this is a bad pattern for its own. But well, it seems that what you want to do.
Edit
Oh one more: Your text file contains some data right? If your data represents some entities (or objects) it would be good to create a POJO for this. I think your text file contains users (right?). Then create a class called Users and parse the text file to get a list of all users in it. Something like:
List<User> users = User.parse("your-file.txt");
Afterwards you have a nice user object and all your ugly parsing is in one central point.

How do I quadruple the integer values in a text file? [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I guess this comes down to reading and writing to the same file. I would like to be able to return the same text file as is input, but with all integer values quadrupled. Should I even be attempting this with Java, or is it better to write to a new file and overwrite the original .txt file?
In essence, I'm trying to transform This:
12
fish
55 10 yellow 3
into this:
48
fish
220 40 yellow 12
Here's what I've got so far. Currently, it doesn't modify the .txt file.
import java.io.*;
import java.util.Scanner;
public class CharacterStretcher
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner( System.in );
System.out.println("Copy and paste the path of the file to fix");
// get which file you want to read and write
File file = new File(keyboard.next());
File file2 = new File("temp.txt");
BufferedReader reader;
BufferedWriter writer;
try {
// new a writer and point the writer to the file
FileInputStream fstream = new FileInputStream(file);
// Use DataInputStream to read binary NOT text.
reader = new BufferedReader(new InputStreamReader(fstream));
writer = new BufferedWriter(new FileWriter(file2, true));
String line = "";
String temp = "";
int var = 0;
int start = 0;
System.out.println("000");
while ((line = reader.readLine()) != null)
{
System.out.println("a");
if(line.contains("="))
{
System.out.println("b");
var = 0;
temp = line.substring(line.indexOf('='));
for(int x = 0; x < temp.length(); x++)
{
System.out.println(temp.charAt(x));
if(temp.charAt(x)>47 && temp.charAt(x)<58) //if 0<=char<=9
{
if(start==0)
start = x;
var*=10;
var+=temp.indexOf(x)-48; //converts back into single digit
}
else
{
if(start!=0)
{
temp = temp.substring(0, start) + var*4 + temp.substring(x);
//writer.write(line.substring(0, line.indexOf('=')) + temp);
//TODO: Currently writes a bunch of garbage to the end of the file, how to write in the middle?
//move x if var*4 has an extra digit
if((var<10 && var>2)
|| (var<100 && var>24)
|| (var<1000 && var>249)
|| (var<10000 && var>2499))
x++;
}
//start = 0;
}
System.out.println(temp + " " + start);
}
if(start==0)
writer.write(line);
else
writer.write(temp);
}
}
System.out.println("end");
// writer the content to the file
//writer.write("I write something to a file.");
// always remember to close the writer
writer.close();
//writer = null;
file2.renameTo(file); //TODO: Not sure if this works...
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Given that this is a pretty quick and simple hack of a formatted text file, I don't think you need to be too clever about it.
Your logic for deciding whether you are looking at a number is pretty complex and I'd say it's overkill.
I've written up a basic outline of what I'd do in this instance.
It's not very clever or impressive, but should get the job done I think.
I've left out the overwriting and reading the input form the console so you get to do some of the implementation yourself ;-)
import java.io.*;
public class CharacterStretcher {
public static void main(String[] args) {
//Assumes the input is at c:\data.txt
File inputFile = new File("c:\\data.txt");
//Assumes the output is at c:\temp.txt
File outputFile = new File("c:\\temp.txt");
try {
//Construct a file reader and writer
final FileInputStream fstream = new FileInputStream(inputFile);
final BufferedReader reader = new BufferedReader(new InputStreamReader(fstream));
final BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile, false));
//Read the file line by line...
String line;
while ((line = reader.readLine()) != null) {
//Create a StringBuilder to build our modified lines that will
//go into the output file
StringBuilder newLine = new StringBuilder();
//Split each line from the input file by spaces
String[] parts = line.split(" ");
//For each part of the input line, check if it's a number
for (String part : parts) {
try {
//If we can parse the part as an integer, we assume
//it's a number because it almost certainly is!
int number = Integer.parseInt(part);
//We add this to out new line, but multiply it by 4
newLine.append(String.valueOf(number * 4));
} catch (NumberFormatException nfEx) {
//If we couldn't parse it as an integer, we just add it
//to the new line - it's going to be a String.
newLine.append(part);
}
//Add a space between each part on the new line
newLine.append(" ");
}
//Write the new line to the output file remembering to chop the
//trailing space off the end, and remembering to add the line
//breaks
writer.append(newLine.toString().substring(0, newLine.toString().length() - 1) + "\r\n");
writer.flush();
}
//Close the file handles.
reader.close();
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
You may want to consider one of these:
Build the new file in memory, rather than trying to write to the same file you are reading from. You could use StringBuilder for this.
Write to a new file, then overwrite the old file with the new one. This SO Question may help you there.
With both of these, you will be able to see your whole output, separate from the input file.
Additionally, with option (2), you don't have the risk of the operation failing in the middle and giving you a messed up file.
Now, you certainly can modify the file in-place. But it seems like unnecessary complexity for your case, unless you have really huge input files.
At the very least, if you try it this way first, you can narrow down on why the more complicated version is failing.
You cannot read and simultaneously write to the same file, because this would modify the text you currently read. This means, you must first write a modified new file and later rename it to the original one. You probably need to remove the original file before renameing.
For renaming, you can use File.renameTo or see one of the many SO's questions
You seem to parse integers in your code by collecting single digits and adding them up. You should consider using either a Scanner.nextInt or employ Integer.parseInt.
You can read your file line by line, split the words at white space and then parse them and check if it is either an integer or some other word.

I want to read a text file, split it, and store the results in an array

I have a text file which has 10 fields(columns)each separated by a tab.And i have several such rows.I wish to read the text file, split it for every column, using a "tab" delimiter and then storing it in an array of 10 columns and unlimited rows.Can that be done?
An array can't have "unlimited rows" - you have to specify the number of elements on construction. You might want to use a List of some description instead, e.g. an ArrayList.
As for the reading and parsing, I'd suggest using Guava, particularly:
Files.newReaderSupplier
CharStreams.readLines
Splitter
(That lets you split the lines as you go... alternatively you could use Files.readLines to get a List<String>, and then process that list separately, again using Splitter.)
BufferedReader buf = new BufferedReader(new FileReader(fileName));
String line = null;
List<String[]> rows = new ArrayList<String[]>();
while((line=buf.readLine())!=null) {
String[] row = line.split("\t");
rows.add(row);
}
System.out.println(rows.toString()); // rows is a List
// use rows.toArray(...) to convert to array if necessary
Here is a simple way to load a .txt file and store it into a array for a set amount of lines.
import java.io.*;
public class TestPrograms {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String conent = new String("da");
String[] daf = new String[5];//the intiger is the number of lines +1 to
// account for the empty line.
try{
String fileName = "Filepath you have to the file";
File file2 = new File(fileName);
FileInputStream fstream = new FileInputStream(file2);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
int i = 1;
while((conent = br.readLine()) != null) {
daf[i] = conent;
i++;
}br.close();
System.out.println(daf[1]);
System.out.println(daf[2]);
System.out.println(daf[3]);
System.out.println(daf[4]);
}catch(IOException ioe){
System.out.print(ioe);
}
}
}

Categories

Resources