reading comma separated text files of different lengths in java - java

so I have a text file and i am trying to read line by line and then populate my array list.
a sample text file is shown below:
10,11,11/10/2021,24,1,2
11,12,11/10/2021,1,2,3
12,13,11/10/2021,24,5
13,14,11/10/2021,1,11,32,2
14,15,11/10/2021,1,9,8
I have been able to read in the first 4 elements (ID,ID,date,price)
and then i need to populate the other elements on that line into an array list (all elements after price)
the problem I am having is that it populates all the other lines into the array list and just not the remaining elements for the one line.
here is the code
int ID = 0;
int spareID = 0;
String date = "";
float fee = 0;
ArrayList<String> limits = new ArrayList<String>();
ArrayList<Import> imports= new ArrayList<Imports>();
File myfile = new File("file.txt");
try {
Scanner inputFile = new Scanner(myfile);
inputFile.useDelimiter(",");
// setting comma as delimiter pattern
while (inputFile.hasNextLine()) {
ID = inputFile.nextInt();
SpareID = inputFile.nextInt();
date = inputFile.next();
fee = inputFile.nextFloat();
while (inputFile.hasNext()) {
limits.add(inputFile.next());
}
Import import = new Import(ID, spareID, fee, date, limits);
imports.add(import);
}
inputFile.close();
} catch (FileNotFoundException e) {
System.out.println("error: can not find file");
}
the array list is capturing the rest of the text file when i need it to capture just the remaining elements on that line.
Edit: the first 4 elements of the line will all go into a different variable and then I need the rest or the elements on that line only to go into the array list

Use Scanner.nextLine() to get a single line, then create a second Scanner with that line to parse it contents.
Scanner inputFile = new Scanner(myfile);
while (inputFile.hasNextLine()) {
Scanner line = new Scanner(inputFile.nextLine());
// setting comma as delimiter pattern
line.useDelimiter(",");
ID = line.nextInt();
SpareID = line.nextInt();
date = line.next();
fee = line.nextFloat();
while (line.hasNext()) {
limits.add(line.next());
}
}
inputFile.close();

Related

reading csv file using scanner in java

public void readCases(String filename) throws IOException {
records.clear(); //name of list is records
try (Scanner input = new Scanner(new File(filename))){
input.nextLine();
while (input.hasNext()){
String text = input.nextLine();
String[] element = text.split(",");
for(int i = 0; i<=3; i++){
if(element[i].equals(' ')){
throw new DatasetException("column missing in csv");
}
}
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-uuuu");
LocalDate date = LocalDate.parse(element[0], formatter);
int europeCases = Integer.parseInt(element[1]);
int asiaCases = Integer.parseInt(element[2]);
int africaCases = Integer.parseInt(element[3]);
CaseRecord caseRecord = new CaseRecord(date, europeCases, asiaCases, africaCases);
addRecord(caseRecord); //this adds caseRecords to records
}
}
}
I am trying to clear an old list, then trying to read a CSV file and loading the list into the list. I'm not really sure where I'm going wrong.
The list contains 4 fields with types
DateTime
int
int
int
and is in the form
2020-10-08,4,41,0
The top line reads
Date,Europe,Asia,Africa
and I want to skip this first line when loading the data into the list.
You can try Java lambda for reading lines of file, skip(1) to skip first line
//read file into stream, try-with-resources
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
stream.skip(1).forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}

Read data from file and convert to key value pair

I have the below integers in File :
758 29
206 58
122 89
I have to read these integers in an integer array and then need to store the values in key value pair. Then print the output as :
Position 29 has been initialized to value 758.
Position 89 has been initialized to value 122.
I have tried as of now :
private static Scanner readFile() {
/*
* Your program will prompt for the name of an input file and the read
* and process the data contained in this file. You will use three
* integer arrays, data[], forward[] and backward[] each containing 100
* elements
*/
int data[] = new int[100];
int forward[] = new int[100];
int backward[] = new int[100];
System.out.print("Please enter File Name : ");
#SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);
String filename = scanner.nextLine();
File inputFile = new File(filename);
Scanner linReader = null;
try {
linReader = new Scanner(new File(filename));
while (linReader.hasNext()) {
String intStringSplit = linReader.nextLine();
String[] line = intStringSplit.split("\t",-1);
data = new int[line.length];
for (int i = 0; i < data.length; i++) {
data[i] = Integer.parseInt(line[i]);
}
System.out.println(data);
}
linReader.close();
} catch (Exception e) {
System.out.println("File Not Found");
}
return linReader;
}
I am not able to figure out how to get the key and value from the read data.
When posting information related to your question it is very important that you provide the data (in file for example) exactly as it is intended in reality so that we can make a more positive determination as to why you are experiencing difficulty with your code.
What you show as an in file data example indicates that each file line (which contains actual data) consists of two specific integer values. The first value being the initialization value and the second being the position value.
There also appears to be a blank line after ever line which contains actual data. This really doesn't matter since the code provided below has a code line to take care of such a thing but it could be the reason as to why you may be having difficulty.
To me, it looks like the delimiter used to separate the two integer values in each file line is indeed a whitespace as #csm_dev has already mentioned within his/her comment but you claim you tried this in your String.split() method and determined it is not a whitespace. If this is truly the case then it will be up to you to determine exactly what that delimiter might be. We couldn't possibly tell you since we don't have access to the real file.
You declare a File object within your provided code but yet nowhere do you utilize it. You may as well delete it since all it's doing is sucking up oxygen as far as I'm concerned.
When using try/catch it's always good practice to catch the proper exceptions which in this case is: IOException. It doesn't hurt to also display the stack trace as well upon an exception since it can solve a lot of your coding problems should an exception occur.
This code should work:
private static Scanner readFile() {
/*
* Your program will prompt for the name of an input file and the read
* and process the data contained in this file. You will use three
* integer arrays, data[], forward[] and backward[] each containing 100
* elements
*/
int data[] = new int[100];
int forward[] = new int[100];
int backward[] = new int[100];
System.out.print("Please enter File Name : ");
Scanner scanner = new Scanner(System.in);
String filename = scanner.nextLine();
File inputFile = new File(filename); // why do you have this. It's doing nothing.
Scanner linReader = null;
try {
linReader = new Scanner(new File(filename));
while (linReader.hasNext()) {
String intStringSplit = linReader.nextLine();
// If the file line is blank then just
// continue to the next file line.
if (intStringSplit.trim().equals("")) { continue; }
// Assuming at least one whitespace is used as
// the data delimiter but what the heck, we'll
// use a regular expression within the split()
// method to handle any number of spaces between
// the integer values.
String[] line = intStringSplit.split("\\s+");
data = new int[line.length];
for (int i = 0; i < line.length; i++) {
data[i] = Integer.parseInt(line[i]);
}
System.out.println("Position " + data[1] +
" has been initialized to value " +
data[0] + ".");
// do whatever else you need to do with the
// data array before reading in the next file
// line......................................
}
linReader.close();
}
catch (IOException ex) {
System.out.println("File Not Found");
ex.printStackTrace();
}
return linReader;
}

How do I read a position of a list of lines in text file

I am building a freight management system. I want to list out the intermediate ports available between the source and destination after the user has input the source port and destination port. But I don't know how to do that. I saved the port name and distance of each port in the text file where one line for each port. The location variable is used to calculate the distance between source and destination. I wanted to use the position variable to locate the ports in between the source and destination.
Newes;10;
Harrytown;25;
Truy;33;
East Port;47;
Athens;56;
Nasky;71;
private int location, location1, position, position1;
private String source, destination;
public void choosePort(){
Scanner sc = new Scanner(System.in);
int i = 0;
System.out.println("Please enter the source.");
source = sc.nextLine();
System.out.println("Please enter the destination.");
destination = sc.nextLine();
try{
File f = new File("Port.txt");
Scanner file = new Scanner(f);
while(file.hasNextLine()){
String line = file.nextLine();
String[] split = line.split(";");
if(split[0].equals(source)){
location = Integer.parseInt(split[1]);
position = i;
}
else if(split[0].equals(destination)){
location1 = Integer.parseInt(split[1]);
position1 = i;
}
i++;
}
file.close();
}
catch(IOException e){
System.out.println(e);
}
If I understand your question correctly, you want ports displayed between source and destination. For example, if a user selects 'Newes" as a starting point and 'Trury' as a destination, you would like 'Harrytown' displayed as an intermediate. There are several ways you can do this. The easiest way, I believe is to use a second scanner to scan word for word, a delimiter, and a print statement inside that while loop.
while(file.hasNextLine())
{
String line = file.nextLine();
Scanner sff = new Scanner(line);
sff.useDelimiter(";"); // scanner will see ';' and skip over it
String temp1 = sff.next;
if ( source.equals(temp1))
{
System.out.println(file.nextLine());
}
After this, just complete out the code. write another file.nextLine() to see if it matches destination, if it does not, print out the line. When sff matches the destination, print out that final line then insert a break statement.
something quick like.
boolean isPrint = false;
while(file.hasNextLine()){
String line = file.nextLine();
String[] split = line.split(";");
if(split[0].equals(destination)){
isPrint = false;
}
if (isPrint) { System.out.println(split[1]);}
if(split[0].equals(source)){
print = true;
}
}

Object[] cannot be converted to String[]

The goal of my code is to replace a certain text value within my .CSV file with the user input of a text field.
My .CSV file has values delimited by commas: hey,hi. If I'm just wanting to replace 'hey' then I would gather the input from the text field and replace 'hey' with 'bye'. Output: bye,hi.
In my code, I believe I am reading in my file and writing the contents of the file to a list, delimited by commas.
I will then iterate through the list and replace an instance of the user input within the list, with another user input and write it back to file.
However, I cannot write it back to file as I'm getting the Object[] cannot be converted to String[] error. Thus I'm stuck as to how to replace the instance of user input within the text file.
Here's my code:
try{
//Convert user input into strings
String strSerial = editSerialField.getText();
String strLocation = editLocationField.getText();
//Read existing file
CSVReader reader = new CSVReader(new FileReader("test test.txt"), ',');
List myEntries = reader.readAll();
//Iterate through my array
for (int i = 0; i < myEntries.size(); i++)
{
//If an entry matches the user input
if (myEntries.get(i).equals(strSerial))
{
//Set the match to the user input from strLocation
myEntries.set(i, strLocation);
break;
}
}
//Write to existing file
CSVWriter writer = new CSVWriter(new FileWriter("test test.txt"), ',');
//Error is here**********************
//Write the new string with the replaced word OVER the same file
writer.writeNext(myEntries.toArray(new String[myEntries.size()]));
writer.close();
}catch (IOException e)
{
System.out.println(e);
}
}
How do I modify my code so that it writes my changes to the .CSV file?
For a start writeNext will write on line at a time, so you need to loop.
Secondly consider using not a raw List but using generics.
Thirdly, it may be cleaner to write as you go
and lastly, each line will contain an Array of Strings
consider this code (not tested)
CSVReader reader = new CSVReader(new FileReader("test test.txt"), ',');
List<String []> myEntries = reader.readAll();
reader.close ();
CSVWriter writer = new CSVWriter(new FileWriter("test test.txt"), ',');
//Iterate through my array
for (String [] line : myEntries)
{
ArrayList<String> newLine = new ArrayList <String>();
for (String word : line) {
{
String newVal = word.replace(strSerial, strLocation);
newLine.add (newVal);
}
writer.writeNext(newLine.toArray(new String[newLine.size()]));
}
Your problem is/ starts at this line:
List myEntries = reader.readAll();
I assume that you did not noticed that the return type of the method readAll() is
List<String[]>
If for example your test file looks like :
hey, hi
hallo, hello
sth, sthelse
After calling readAll() your variable myEntries will be a list of string arrays; each array representing each row in your file and each string from that row as element of the array
myEntries : [hey, hi]
[hallo, hello]
[sth, sthelse]
Keeping this in mind the next issue is
if (myEntries.get(i).equals(strSerial))
where you try to compare a String[] with a String which will not be true.
Try it as follows :
try{
//Convert user input into strings
String strSerial = editSerialField.getText();
String strLocation = editLocationField.getText();
CSVReader reader = new CSVReader(new FileReader("test test.txt"), ',');
// valid but not a good practice how you declare your variable before
// List myEntries = reader.readAll(); // List of what??
List<String[]> myEntries = reader.readAll();
for (String[] row : myEntries){ // go through each array from your list representing a row in your file
for (int i = 0; i < row.length; i++){ //go through each element of that array
if (row[i].equalsIgnoreCase(strSerial)){
row[i] = strLocation;
}
}
}
//add the parameter CSVWriter.NO_QUOTE_CHARACTER to prevent opencsv from writing quotes to file
CSVWriter writer = new CSVWriter(new FileWriter("test test.txt"), ',',CSVWriter.NO_QUOTE_CHARACTER);
for (String[] row : myEntries){
writer.writeNext(row);
}
writer.close();
}catch (IOException e){
System.out.println(e);
}
Not really important but i would prefer test.csv instead of test.txt as file name as long as you store comma-separated values in there.

Scanning, spliting and assigning values from a text file

I'm having trouble scanning a given file for certain words and assigning them to variables, so far I've chosen to use Scanner over BufferedReader because It's more familiar. I'm given a text file and this particular part I'm trying to read the first two words of each line (potentially unlimited lines) and maybe add them to an array of sorts. This is what I have:
File file = new File("example.txt");
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] ary = line.split(",");
I know It' a fair distance off, however I'm new to coding and cannot get past this wall...
An example input would be...
ExampleA ExampleAA, <other items seperated by ",">
ExampleB ExampleBB, <other items spereated by ",">
...
and the proposed output
VariableA = ExampleA ExampleAA
VariableB = ExampleB ExampleBB
...
You can try something like this
File file = new File("D:\\test.txt");
Scanner sc = new Scanner(file);
List<String> list =new ArrayList<>();
int i=0;
while (sc.hasNextLine()) {
list.add(sc.nextLine().split(",",2)[0]);
i++;
}
char point='A';
for(String str:list){
System.out.println("Variable"+point+" = "+str);
point++;
}
My input:
ExampleA ExampleAA, <other items seperated by ",">
ExampleB ExampleBB, <other items spereated by ",">
Out put:
VariableA = ExampleA ExampleAA
VariableB = ExampleB ExampleBB
To rephrase, you are looking to read the first 2 words of a line (everything before the first comma) and store it in a variable to process further.
To do so, your current code looks fine, however, when you grab the line's data, use the substring function in conjunction with indexOf to just get the first part of the String before the comma. After that, you can do whatever processing you want to do with it.
In your current code, ary[0] should give you the first 2 words.
public static void main(String[] args)
{
File file = new File("example.txt");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line = "";
List l = new ArrayList();
while ((line = br.readLine()) != null) {
System.out.println(line);
line = line.trim(); // remove unwanted characters at the end of line
String[] arr = line.split(",");
String[] ary = arr[0].split(" ");
String firstTwoWords[] = new String[2];
firstTwoWords[0] = ary[0];
firstTwoWords[1] = ary[1];
l.add(firstTwoWords);
}
Iterator it = l.iterator();
while (it.hasNext()) {
String firstTwoWords[] = (String[]) it.next();
System.out.println(firstTwoWords[0] + " " + firstTwoWords[1]);
}
}

Categories