how to update the file without creating new file - java

My code does not update the exist file. So i create new file but i want to do with the same file and update it. Anyone know how to do it ? my code is here and a picture of what im doing
try (BufferedWriter writer = new BufferedWriter(new FileWriter("project-output.csv"))) {
try (BufferedReader reader = new BufferedReader(new FileReader("project.csv"))) {
String line;
while ((line = reader.readLine()) != null) {
String[] cols = line.split(",");
System.out.println("Please choose a criteria (2-7): ");
final int subjectToGiveMark = in.nextInt(); // for creativity is 2
System.out.println("Please enter a mark: ");
final int mark = in.nextInt(); // which mark should be given
cols[subjectToGiveMark] = Integer.toString(mark);
// Here is where you write the output:
writer.write(String.join(",", cols));
writer.newLine();
}
writer.flush();
}
}
enter image description here

Do it as follows:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
String line;
List<String> dataLines = new ArrayList<String>();
final int COLS = 6;
String[][] data = null;
try (BufferedReader br = new BufferedReader(new FileReader("project.csv"))) {
while ((line = br.readLine()) != null) {
dataLines.add(line);
}
// Initialise data[][] with the data from project.csv
data = new String[dataLines.size()][COLS];
for (int i = 0; i < dataLines.size(); i++) {
data[i] = dataLines.get(i).split(",");// Split on comma
}
// Display Sarah's marks in Achievement (15)
System.out.println(data[2][1] + "'s marks in Achievement (15) is " + data[2][3]);
// Display Harry's marks in Knowledge (25)
System.out.println(data[3][1] + "'s marks in Knowledge (25) is " + data[3][4]);
} catch (Exception e) {
e.printStackTrace();
}
// Update the file
try (BufferedWriter writer = new BufferedWriter(new FileWriter("project.csv"))) {
// Increasing Sarah's marks in Achievement by 1
int m = Integer.parseInt(data[2][3]) + 1;
data[2][3] = String.valueOf(m);
// Decreasing Harry's marks in Knowledge by 1
m = Integer.parseInt(data[3][4]) - 1;
data[3][4] = String.valueOf(m);
//Write the updated data to file
for (String[] row : data) {
writer.write(String.join(",", row) + System.lineSeparator());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
Sarah's marks in Achievement (15) is 13
Harry's marks in Knowledge (25) is 24
Original content of project.csv:
Student Id,Student Name,Creativity (10),Achievement (15),Knowledge (25),Documentation (25)
F1233,Bill,8,12,20,18
F2345,Sarah,9,13,22,23
F3456,Harry,9,14,24,24
New content of project.csv:
Student Id,Student Name,Creativity (10),Achievement (15),Knowledge (25),Documentation (25)
F1233,Bill,8,12,20,18
F2345,Sarah,9,14,22,23
F3456,Harry,9,14,23,24
Example of updating the data interactively:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException, IOException {
String line;
List<String> dataLines = new ArrayList<String>();
final int COLS = 6;
String[][] data = null;
try (BufferedReader br = new BufferedReader(new FileReader("project.csv"))) {
while ((line = br.readLine()) != null) {
dataLines.add(line);
}
// Initialise data[][] with the data from project.csv
data = new String[dataLines.size()][COLS];
for (int i = 0; i < dataLines.size(); i++) {
data[i] = dataLines.get(i).split(",");// Split on comma
}
}
// Update the file
try (BufferedWriter writer = new BufferedWriter(new FileWriter("project.csv"))) {
Scanner in = new Scanner(System.in);
// Updating existing record
System.out.println("Updating " + data[2][1] + "'s marks in a subject...");
System.out.print(
"Enter the subject number[2 for Creativity, 3 for Achievement, 4 for Knowledge, 5 for Documentation]: ");
int col = Integer.parseInt(in.nextLine());
if (col >= 2 && col <= 5) {
System.out.print("Enter marks in the subject: ");
data[2][col] = in.nextLine();
// Write the updated data to file
for (String[] row : data) {
writer.write(String.join(",", row) + System.lineSeparator());
}
}
// Adding a new record
System.out.println("Adding a new record...");
String[] record = new String[COLS];
System.out.print("Enter student ID: ");
record[0] = in.nextLine();
System.out.print("Enter student name: ");
record[1] = in.nextLine();
System.out.print(
"Enter marks in Creativity (10), Achievement (15), Knowledge (25), and Documentation (25): ");
System.arraycopy(in.nextLine().split("\\s+"), 0, record, 2, COLS - 2);
writer.write(String.join(",", record) + System.lineSeparator());
}
}
}
A sample run:
Updating Sarah's marks in a subject...
Enter the subject number[2 for Creativity, 3 for Achievement, 4 for Knowledge, 5 for Documentation]: 2
Enter marks in the subject: 7
Adding a new record...
Enter student ID: F4567
Enter student name: Richard
Enter marks in Creativity (10), Achievement (15), Knowledge (25), and Documentation (25): 8 12 20 21
New content of project.csv:
Student Id,Student Name,Creativity (10),Achievement (15),Knowledge (25),Documentation (25)
F1233,Bill,8,12,20,18
F2345,Sarah,7,14,22,23
F3456,Harry,9,14,23,24
F4567,Richard,8,12,20,21

can you try
// Read existing file
CSVReader reader = new CSVReader(new FileReader(inputFile), ',');
List<String[]> csvBody = reader.readAll();
// get CSV row column and replace with by using row and column
csvBody.get(row)[col] = replace;
reader.close();
// Write to CSV file which is open
CSVWriter writer = new CSVWriter(new FileWriter(inputFile), ',');
writer.writeAll(csvBody);
writer.flush();
writer.close();

Related

There's some problem in the loop and it's repeating 12 times help if possible

This is part of my code which I am doing under my college project so basically I am making a simple plagiarism detection using two string matching algorithms and using it in the main class and for I did some mistakes in loops so because of that my output is repeating 12 times and checked my code again and again but can't really figure out where I went wrong I really need someone to help me with this I have to submit this by end of this month I am attaching photo of my output Output
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class MClass {
public static void main(String[] args) throws IOException {
String ptrnLine, textLine,inpLine,sFilePath,srcLine;
int srcLineIndex=1, inpLineIndex=1;
KMP kmpComponent;
RabinKarp rkComponent;
int inputLen,srcLen,patterntextLength;
double kmpSimRatio = 0;
int rkNumberOfMatches;
int fullTextLength=0, fullPatternLength=0;
boolean rkPlagarismStatus = false;
final File folder = new File("D:\\Project");
File fileKmp = new File("kmp.txt");
File fileRK = new File("rk.txt");
int coun = 0;
fileKmp.delete();
fileRK.delete();
FileWriter outKmpFile = new FileWriter("kmp.txt", true);
FileWriter outRkFile = new FileWriter("rk.txt", true);
for (final File fileEntry : folder.listFiles()) {
sFilePath = fileEntry.getPath();
srcLineIndex=1;
File sourceFile = new File("source.txt");
File inputFile = new File( "input.txt");
#SuppressWarnings("resource")
BufferedReader sReader = new BufferedReader( new FileReader(sourceFile));
while((srcLine = sReader.readLine())!=null)
{
BufferedReader reader = new BufferedReader( new FileReader(inputFile));
inpLineIndex=1;
fullTextLength = fullTextLength+srcLine.length();
while((inpLine = reader.readLine())!=null)
{
inputLen = inpLine.length();
srcLen = srcLine.length();
if(inputLen>0 && srcLen>0)
{
if(srcLen>inputLen)
{
textLine = srcLine;
ptrnLine = inpLine;
}
else
{
textLine = inpLine;
ptrnLine = srcLine;
}
patterntextLength = ptrnLine.length();
if(coun<1)
{
fullPatternLength = fullPatternLength+ ptrnLine.length();
}
// KMP Algorithm
kmpComponent = new KMP();
if(patterntextLength!=0)
{ kmpSimRatio= (kmpComponent.searchSubString(textLine, ptrnLine)/(double)(patterntextLength));
}
System.out.println("KMP Algorithm Result");
System.out.println("Similarity ratio = "+kmpSimRatio*100.000+" Line Number of the input file= "+inpLineIndex+
" Line Number of the source file = "+srcLineIndex);
System.out.println("------------------------------------------------------------------------------------------------------------------------------------------");
PrintWriter outPKmpFile = new PrintWriter(outKmpFile);
if(kmpSimRatio>0.60)
{ outPKmpFile.append("Line "+inpLineIndex + " of the input file has plagarised " +kmpSimRatio*100.000+
"% from line "+srcLineIndex +" of the source file \n");
}
//Rabin Karp Algorithm
rkComponent = new RabinKarp();
if(patterntextLength!=0)
{
rkNumberOfMatches = rkComponent.search(ptrnLine,textLine);
if(rkNumberOfMatches>0)
{
rkPlagarismStatus = true;
}
else
{
rkPlagarismStatus =false;
}
if(rkPlagarismStatus)
{ System.out.println("Rabin Karp Algorithm Result");
System.out.println(" Line Number of the input file= "+inpLineIndex+ " is plagarised from" +
" Line Number of the source file = "+srcLineIndex+" Number of times string matched was "+rkNumberOfMatches);
System.out.println("------------------------------------------------------------------------------------------------------------------------------------------");
PrintWriter outPRkFile = new PrintWriter(outRkFile);
outPRkFile.append("Line "+inpLineIndex + " of the input file has plagarised from line "+srcLineIndex +" of the source file "+fileEntry.getName()+
" "+rkNumberOfMatches+" time string matching found\n");
}
}
inpLineIndex++;
}
}
coun++;
srcLineIndex++;
}
}
outKmpFile.close();
outRkFile.close();
}
}

read txt file and store each category(make,color,year) into a different ArrayList

trying to read txt file and store each category(make,color,year) into different ArrayLists and then display all the data in the array list.
what im getting
*****Welcome *****
setup
so by going System.out.println(make.get(i)) etc. I get
toyota
subaru
honda
blue
black
white
2010
2001
2003
the text file looks like this
3
#car
#make
Toyota
#Color
Blue
#year
2010
##
#car
#make
subaru
#color
black
#year
2003
##
#car
#make
honda
#Color
white
#year
2001
##
the 3 at the tells how much cars are in the garage
the "##" represents the end of the car details
code
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
public class testApp {
static ArrayList<String> year= new ArrayList<>();
static ArrayList<String> make = new ArrayList<>();
static ArrayList<String> colors = new ArrayList<>();
private static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("*****Welcome*****");
try {
garage();
} catch (Exception e) {
//System.out.println(e.getMessage());
}
}
public static void garage() throws NumberFormatException, IOException {
System.out.println("setup");
String filename = "garage.txt";
String showError = "Error input file " + filename + " is not formmated properly.";
BufferedReader reader = new BufferedReader(new FileReader(new File(filename)));
String line = reader.readLine();
if (line == null) {
reader.close();
throw new IOException(showError);
}
int numCar= Integer.parseInt(line);
System.out.println("num ques " + numCar);
int carCount = 0;
//loop to look for each car
while ((line = reader.readLine()) != null && carCount < numCar) {
// System.out.println("reading");
if (line.equals("#car")) {
// System.out.println("q");
while ((line = reader.readLine().trim()) != null) {
if (!line.equals("##")) {
//reads car
if (line.equals("#make")) {
make.add(reader.readLine());
System.out.println("q 1 "+make.get(0));
}
if (line.equals("#color")) {
System.out.println("make orig= " + reader.readLine());
colors.add(reader.readLine());
}
if (line.equals("#year")) {
year.add(reader.readLine());
System.out.println("ans orig= " + reader.readLine());
//color = readAnswer(reader.readLine(),car);
}
} else {
break;
}
}
carCount++;
}
}
for (int i = 0; i < 3; i++) {
System.out.println(make.get(i));
System.out.println(year.get(i));
System.out.println(colors.get(i));
}
}
}
Try this - one change in line 13 (garage.txt) making it color -> Color.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.StringJoiner;
public class TestApp {
public static void main(String[] args) throws IOException {
String filename = "garage.txt";
File file = new File(filename);
FileReader reader = new FileReader(file);
BufferedReader br = new BufferedReader(reader);
String line = null;
StringJoiner joiner = new StringJoiner("");
int count = 0;
while ((line = br.readLine()) != null) {
if (count == 0) {
count = Integer.parseInt(line.trim());
} else {
joiner.add(line.trim());
}
}
String[] carDetails = joiner.toString().split("###");
ArrayList<String> cars = new ArrayList<>();
ArrayList<String> colors = new ArrayList<>();
ArrayList<String> years = new ArrayList<>();
for (String details : carDetails) {
String car = details.split("#make")[1].split("#Color")[0];
cars.add(car);
String color = details.split("#make")[1].split("#Color")[1].split("#year")[0];
colors.add(color);
String year = details.split("#make")[1].split("#Color")[1].split("#year")[1];
year = year.replace("#", "");
years.add(year);
}
for (String car : cars) {
System.out.println(car);
}
System.out.println("\n");
for (String color : colors) {
System.out.println(color);
}
System.out.println("\n");
for (String year : years) {
System.out.println(year);
}
br.close();
}
}

How to copy each column in a separate file

I have a txt file that contains 24 columns separated with \t. The first column contains words and the other 23 columns contain int (0 or 1). I need to put each column in a separate file
For example:
file.txt
xyz 0 1
abc 0 1
the resulting files would be:
file 1:
0
0
file 2:
1
1
The code is as follows:
for (int i=24; i>0; i--){
//copy the last word (column) in list
for (String str: list) {
String ch = str.substring(str.length() - 1);
col_list.add(ch);
}
//write the column in file
FileWriter write = new FileWriter(+i+".txt");
for(String str1: col_list) {
write.write(str1+"\n");
}
write.close();
col_list = new ArrayList<String>();
//remove last column from list
for(String str2: list) {
str2.substring(str2.length()-3, str2.length()-1);
}
}
The result files contain only the content of the last column
file 1:
1
1
file 2:
1
1
How about going for it this way? Change num_files to 24 and you should be good to go.
import java.util.ArrayList;
import java.util.Scanner;
import java.io.FileWriter;
import java.io.File;
class Test {
public static void main(String a[]) {
File myFile = new File("Test.txt");
try {
int num_files = 3;
Scanner scanner = new Scanner(myFile);
String list[];
while (scanner.hasNextLine()) {
list = scanner.nextLine().split("\t");
for (int i = 0; i < num_files; i++) {
FileWriter write = new FileWriter((i + 1) + ".txt", true); //you want to open it in append mode
write.write(list[i] + "\n");
write.close();
}
}
} catch (Exception e) {
}
}
}
Input and Output Files
Let me know if this solves your problem. Cheers!

Compare two ArrayLists and print data of merged arraylist based on condition

The two files that I use are
1. Details.txt
Code|Account No.|City
100051001|999001|Delhi
200051003|999002|Kanpur
180051012|999003|Jammu
2.Sal.txt
Code|Amount
100051001|100
200051001|200
180051012|123
Output should be
100051001 999001 Amount 100 INR Delhi
180051012 999003 Amount 123 INR Jammu
The code that i have tried is as under:-
//Code to get the output
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
public class compareArrayList {
public static void main(String[] args) throws FileNotFoundException {
String credit_file_name ="C:/transfer/Sal.txt";
String file_branches ="C:/transfer/Details.txt";
BufferedReader reader0;
BufferedReader reader1;
ArrayList<String> branch_list = new ArrayList<String>();
ArrayList<String> credit_file = new ArrayList<String>();
try {
reader0 = new BufferedReader(new FileReader(file_branches));
reader1 = new BufferedReader(new FileReader(credit_file_name));
String data ="";
String acct_num = "";
String city ="";
String amount1 ="";
String line0 = reader0.readLine();
String line1 = reader1.readLine();
while (line0 != null) {
branch_list.add(line0);
line0 = reader0.readLine();
}
Collections.sort(branch_list);
reader0.close();
while (line1 != null) {
credit_file.add(line1);
line1 = reader1.readLine();
}
Collections.sort(credit_file);
reader1.close();
for ( int i = 0; i < branch_list.size(); i++){
for (int j = 0; j < credit_file.size(); j++) {
int firstIndex0 = branch_list.get(i).indexOf('|',1);
int secondIndex0 = branch_list.get(i).indexOf('|', firstIndex0 +1);
int firstIndex1 = credit_file.get(j).indexOf('|',1);
acct_num = branch_list.get(i).substring(firstIndex0+1, secondIndex0);
city = branch_list.get(i).substring(secondIndex0+1, branch_list.get(i).length());
amount1 = credit_file.get(j).substring(firstIndex1+1, credit_file.get(j).length());
if ( branch_list.get(i).substring(0, 9).equals(credit_file.get(j).substring(0, 9)))
data = branch_list.get(i).substring(0, 9) + " " + acct_num + " Amount " + amount1 + " INR " + city;
}
System.out.println(data);
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}
Output that i am getting is as under:-
100051001 999001 Amount 100 INR Delhi
180051012 999003 Amount 123 INR Jammu
180051012 999003 Amount 123 INR Jammu
There is duplicate of records in this.
You can use map to eliminate duplicates values. I have assumed that acc_no is unique so modified code is:-
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class compareArrayList {
public static void main(String[] args) throws FileNotFoundException {
String credit_file_name = "C:/transfer/Sal.txt";
String file_branches = "C:/transfer/Details.txt";
BufferedReader reader0;
BufferedReader reader1;
ArrayList<String> branch_list = new ArrayList<String>();
ArrayList<String> credit_file = new ArrayList<String>();
try {
reader0 = new BufferedReader(new FileReader(file_branches));
reader1 = new BufferedReader(new FileReader(credit_file_name));
String data = "";
Long acct_num = null;
String city = "";
String amount1 = "";
String line0 = reader0.readLine();
String line1 = reader1.readLine();
Map<Long, String> maps = new HashMap<>();
while (line0 != null) {
branch_list.add(line0);
line0 = reader0.readLine();
}
Collections.sort(branch_list);
reader0.close();
while (line1 != null) {
credit_file.add(line1);
line1 = reader1.readLine();
}
Collections.sort(credit_file);
reader1.close();
for (int i = 0; i < branch_list.size(); i++) {
for (int j = 0; j < credit_file.size(); j++) {
int firstIndex0 = branch_list.get(i).indexOf('|', 1);
int secondIndex0 = branch_list.get(i).indexOf('|', firstIndex0 + 1);
int firstIndex1 = credit_file.get(j).indexOf('|', 1);
acct_num = new Long(branch_list.get(i).substring(firstIndex0 + 1, secondIndex0));
city = branch_list.get(i).substring(secondIndex0 + 1, branch_list.get(i).length());
amount1 = credit_file.get(j).substring(firstIndex1 + 1, credit_file.get(j).length());
if (branch_list.get(i).substring(0, 9).equals(credit_file.get(j).substring(0, 9)))
data = branch_list.get(i).substring(0, 9) + " " + acct_num + " Amount " + amount1 + " INR " + city;
maps.put(acct_num, data);
}
//System.out.println(data);
}
for (String value : maps.values())
System.out.println(value);
} catch (IOException e) {
e.printStackTrace();
}
}
}
This is the approach I will take for solving this type of problem.
I would use a library that can read CSV file like supercsv or
opencsv to read the files and convert them into Java objects.
Create a Java class that can represent your data
Create a map and add the items from the first file with acct_num as key
Iterate through the items from the second file and update the map

importing a csv file into a java swing table

I have a csv file of all the stock quotes on in the nyse. first column is symbol second column is the name of the company.
I have a search box and table made in netbeans using the java swing library.
Right now when I enter the name in the box it is returning the correct amount of rows. So for instance if I search GOOG it will only return 2 rows (1 row for the GOOG symbol and one row for the name in the full company name). However the data within the rows is not the correct ones it is just printing the first row of the csv file over and over. here is the code that gets executed when clicking the search button:
package my.Stock;
import java.util.ArrayList;
import java.util.Scanner;
import java.io.BufferedReader;
import java.util.StringTokenizer;
import java.io.FileReader;
import java.io.*;
public class searchy {
public static void doSearch(String s){
javax.swing.JTable resTable = StockUI.stockUI.getResultTable();
javax.swing.table.DefaultTableModel dtm =
(javax.swing.table.DefaultTableModel) resTable.getModel();
while (dtm.getRowCount()> 0 ) dtm.removeRow(0);
String sym = s.trim().toUpperCase();
try {
//csv file containing data
String strFile = "companylist.csv";
//create BufferedReader to read csv file
BufferedReader br = new BufferedReader( new FileReader(strFile));
String strLine = "";
StringTokenizer st = null;
int lineNumber = 0, tokenNumber = 0;
//create arraylist
ArrayList<String> arrayList = new ArrayList<String>();
//read comma separated file line by line
while( (strLine = br.readLine()) != null){
lineNumber++;
//break comma separated line using ","
st = new StringTokenizer(strLine, ",");
while(st.hasMoreTokens()){
//display csv values
tokenNumber++;
arrayList.add(st.nextToken());
//System.out.println("Line # " + lineNumber + ": "+ st.nextToken() + " " + st.nextToken());
} //end small while
//reset token number
tokenNumber = 0;
} //end big while loop
//send csv to an array
Object[] elements = arrayList.toArray();
/*
for(int i=0; i < elements.length ; i++) {
System.out.println(elements[i]);
} */
Scanner input = new Scanner(System.in);
System.out.print("Enter Ticker symbol");
//String sym = input.next().toUpperCase(); //convert to uppercase to match csv
int j=0;
for(int i=0; i < elements.length ; i++) {
if (((String) elements[i]).contains(sym)){
//System.out.println(elements[i]);
dtm.addRow(elements);
j++;
if (j==25) break; //only show this many results
}
}
}
catch(Exception e){
System.out.println("Exception while reading csv file: " + e);
}
}
}
I understand why this is happening but I am not sure how to tell it to print the correct lines since I can't use dtm.addRow(elements[i]);
Any help is greatly appreciated.
Try CSVManager.
I collect csv data for stocks from Yahoo, and, oddly enough, every now and then they mess it up by using a company name with a comma in it, e.g., "Dolby, Inc.". Of course, that throws off the parsing of the CSV file. I don't know if this might be your problem.
John Doner
package recommendation.event.test;
import java.io.FileReader;
import com.csvreader.CsvReader;
public class ReadCSV {
public static void main (String [] args){
try {
CsvReader products = new CsvReader("resources/Event Recommendation Engine Challenge/data/test.csv");
products.readHeaders();
while (products.readRecord())
{
String user = products.get("user");
String event = products.get("event");
String invited = products.get("invited");
String timestamp = products.get("timestamp");
System.out.println(user + " : " + event+" : "+invited+" : "+timestamp);
}
products.close();
}catch (Exception e) {
// TODO: handle exception
}
}
}

Categories