i am trying to use this code to replace field and after the replace is done i like to delete the file. But when i replace the file only 1 line was saved. How should i ensure that the other lines will be saved?
public static void main(String[] args){
AddChips();
}
public static void AddChips() {
File oldFile = new File ("players.dat");
File newFile = new File ("tempchips.dat");
BufferedReader br = null;
BufferedWriter bw = null;
ArrayList<String> player = new ArrayList<String>();
try {
br = new BufferedReader(new FileReader(oldFile));
bw = new BufferedWriter(new FileWriter(newFile));
String line;
Scanner read = new Scanner(System.in);
System.out.println("Please Enter Username");
String UserN = read.nextLine();
System.out.println("Please Enter Chips to Add");
String UserCadd = read.nextLine();
while ((line = br.readLine()) != null) {
String[] details = line.split("\\|");
String Username = details[0];
String Password = details[1];
String Chips = details[2];
int totalChips = (Integer.parseInt(UserCadd)+ Integer.parseInt(Chips));
if (Username.equals(UserN)){
line = Username + "|" + Password + "|" + totalChips;
bw.write(line + System.getProperty("line.separator"));
}
//issue is here
br.close();
bw.close();
oldFile.delete();
newFile.renameTo(oldFile);
//AdminMenu();
}
} catch (Exception e) {
return;
} finally {
try {
if(br != null)
br.close();
} catch (IOException e) {
//
}
try {
if(bw != null)
bw.close();
} catch (IOException e) {
//
}
}
}
Related
Any idea on How I can check if A record is deleted or is there a better way to delete an array of code using bufferedreader and writter?
public static void DeleteData() throws IOException {
try {
Viewrecord();
Scanner strInput = new Scanner(System.in);
String ID, record;
File tempDB = new File("tempdata.txt");
File db = new File("Database.txt");
BufferedReader br = new BufferedReader(new FileReader(db));
BufferedWriter bw = new BufferedWriter(new FileWriter(tempDB));
System.out.println("\t\t Delete An Item \n");
System.out.println("Enter Item ID: ");
ID = strInput.nextLine();
while ((record = br.readLine()) != null) {
String[] data = record.split(":::");
if (data[0].toString().equals(ID))
continue;
{
bw.write(record);
bw.flush();
bw.newLine();
}
}
br.close();
bw.close();
db.delete();
tempDB.renameTo(db);
} catch (IOException ex) {
System.out.println(ex.toString());
}
}
I did try using a boolean inside the while loop
copy part like this(from date to date) I am trying to copy only a part of .CSV file based on the first column (Start Date and Time) data looks like (2019-01-28 10:22:00 AM) but the user have to put it like this (2019/01/28 10:22:00)
this is for windows, java opencsv , this is what I found but dont do what I need exaclty :
like this:
int startLine = get value1 from column csv ;
int endLine = get value2 from column csv;
public static void showLines(String fileName, int startLine, int endLine) throws IOException {
String line = null;
int currentLineNo = 1;
// int startLine = 20056;//40930;
// int currentLineNo = 0;
File currentDirectory = new File(new File(".").getAbsolutePath());
String fromPath = currentDirectory.getCanonicalPath() + "\\Target\\part.csv";
PrintWriter pw = null;
pw = new PrintWriter(new FileOutputStream(fromPath), true);
//pw.close();
BufferedReader in = null;
try {
in = new BufferedReader (new FileReader(fileName));
//read to startLine
while(currentLineNo<startLine) {
if (in.readLine()==null) {
// oops, early end of file
throw new IOException("File too small");
}
currentLineNo++;
}
//read until endLine
while(currentLineNo<=endLine) {
line = in.readLine();
if (line==null) {
// here, we'll forgive a short file
// note finally still cleans up
return;
}
System.out.println(line);
currentLineNo++;
pw.println(line);
}
} catch (IOException ex) {
System.out.println("Problem reading file.\n" + ex.getMessage());
}finally {
try { if (in!=null) in.close();
pw.close();
} catch(IOException ignore) {}
}
}
public static void main(String[] args) throws FileNotFoundException {
int startLine = 17 ;
int endLine = 2222;
File currentDirectory = new File(new File(".").getAbsolutePath());
try {
showLines(currentDirectory.getCanonicalPath() + "\\Sources\\concat.csv", startLine, endLine);
} catch (IOException e) {
e.printStackTrace();
}
// pw.println();
}
Common CSV format uses a comma as a delimiter, with quotations used to escape any column entry that uses them within the data. Assuming that your column one data is consistent with the format you posted, and that I wouldn't have to bother with quotations marks therefor, you could read the columns as:
public static void main(String[] args) {
//This is the path to the file you are writing to
String targetPath = "";
//This is the path to the file you are reading from
String inputFilePath = "";
String line = null;
ArrayList<String> lines = new ArrayList<String>();
boolean add = false;
String startLine = "2019/01/28 10:22:00";
String endLine = "2019/01/28 10:30:00";
String addFlagSplit[] = startLine.replace("/", "-").split(" ");
String addFlag = addFlagSplit[0] + " " + addFlagSplit[1];
String endFlagSplit[] = endLine.replace("/", "-").split(" ");
String endFlag = endFlagSplit[0] + " " + endFlagSplit[1];
try(PrintWriter pw = new PrintWriter(new FileOutputStream(targetPath), true)){
try (BufferedReader input = new BufferedReader(new FileReader(inputFilePath))){
while((line = input.readLine()) != null) {
String date = line.split(",")[0];
if(date.contains(addFlag)) {
add = true;
}else if(date.contains(endFlag)) {
break;
}
if(add) {
lines.add(line);
}
}
}
for(String currentLine : lines) {
pw.append(currentLine + "\n");
}
}catch(FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
File currentDirectory = new File(new File(".").getAbsolutePath());
String targetPath = currentDirectory.getCanonicalPath() + "\\Target\\part.csv";
String inputFilePath = currentDirectory.getCanonicalPath() + "\\Sources\\concat.csv";
String line = null;
ArrayList<String> lines = new ArrayList<String>();
boolean add = false;
String startLine = "2019/01/28 10:22:00";
String endLine = "2019/04/06 10:30:00";
try(PrintWriter pw = new PrintWriter(new FileOutputStream(targetPath), true)){
try (BufferedReader input = new BufferedReader(new FileReader(inputFilePath))){
while((line = input.readLine()) != null) {
String date = line.split(",")[0];
if(date.contains(startLine)) {
add = true;
}else if(date.contains(endLine)) {
break;
}
if(add) {
lines.add(line);
}
}
}
for(String currentLine : lines) {
pw.append(currentLine + "\n");
}
}catch(FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}catch(Exception e) {
e.printStackTrace();
}
}
My program is basically a user's name, and balance, this is stored in a file, when the user updates their profile, I want their balance to update too, but not their name, as they already have it in the file.
The name and balance are split with a comma. In the file it is displayed like this:
Stacey,0.02
(The name is actually a randomly generated number+letter string, but I thought I'd keep it simple here.)
When I try to write to the file with this code, it doesn't write anything.
Code:
btnSaveUserid.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String text = txtUserid.getText().toString();
String balance = beedcoin1Balance.getText().toString();
File file = new File("d:/users/joel/desktop/code/usersid.txt");
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("d:/users/joel/desktop/code/usersid.txt"));
List<String> terms = new ArrayList<String>();
List<String> ttlBalance = new ArrayList<String>();
while ((sCurrentLine = br.readLine()) != null) {
String[] ar = sCurrentLine.split(",");
String userid = ar[0];
terms.add(userid);
System.out.println(terms);
}
if(terms.contains(text)) {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("d:/users/joel/desktop/code/usersid.txt")));
Scanner scanner = new Scanner(file);
while(scanner.hasNextLine());
String line = scanner.nextLine();
String[] ar = line.split(",");
String userid = ar[0];
String bdcv1val = ar[1];
int lineNum = 0;
lineNum++;
if(line.equals(userid)) {
Path path = Paths.get("d:/users/joel/desktop/code/usersid.txt");
Charset charset = StandardCharsets.UTF_8;
String content = new String(Files.readAllBytes(path), charset);
content = content.replace(txtUserid.toString(), txtUserid.toString());
Files.write(path, content.getBytes(charset));
out.println(text + "," + balance);
System.out.println("Successfully printed to usersid.txt");
}
}
else {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("d:/users/joel/desktop/code/usersid.txt")));
out.println(text + "," + balance);
System.out.println("Successfully printed to usersid.txt");
}
} catch (IOException el) {
el.printStackTrace();
} finally {
try {
if(br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
It all takes place in a button's action listener, and this code outputs the "Successfully printed to file" but doesn't actually print it to the file. I'm honestly perplexed, any help would be greatly appreciated.
My Java program has a superclass (ProgettoBase) and two underclasses (ProgettoCorpo and ProgettoOre). I must copy two different csv files (progetti_ora.csv and progetti_corpo.csv) to a list but I can't see the elements of the list when I launch the program.
public void readFile () {
List<String> projects = new ArrayList<>();
System.out.println("My list is: " + projects);
//read 1 progetti_ora
String csvFile = "progetti_ora.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ";";
//read 2 progetti_corpo
String csvFileDue = "progetti_corpo.csv";
BufferedReader brDue = null;
String lineDue = "";
String cvsSplitByDue = ";";
//read file 1
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
String[] vote = line.split(cvsSplitBy);
for(String s : vote)
System.out.println("List one: " + s);
for(int x = 0; x <= 2; x++) {
projects.add(vote[x].toString());
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
System.out.println("OK1");
//read file 2
try {
brDue = new BufferedReader(new FileReader(csvFileDue));
while ((lineDue = brDue.readLine()) != null) {
String[] voteDue = lineDue.split(cvsSplitByDue);
for(String t : voteDue)
System.out.println("Lista file due: " + t);
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
System.out.println("OK2");
}
I was using my code to do a replace line feature. It was working initially but suddenly my new file became blank and the code did not bring me back to the AdminMenu(), as well as the file not being renamed. There is also another issue where if I use "\r\n" there will be a blank line on top of my file which I am trying to remove. I tried using \n after totalChips, but it doesn't seem to work. I could use some advice on this.
output
<Blank File>
expected output
Line1|password|500
Line2|password|600
//ModifiedLine can be either line based on UserName
codes are below
public static void AddChips() {
File oldFileName = new File("players.dat");
File tmpFileName = new File("newplayers.dat");
BufferedReader br = null;
BufferedWriter bw = null;
ArrayList<String> player = new ArrayList<String>();
try {
br = new BufferedReader(new FileReader(oldFileName));
bw = new BufferedWriter(new FileWriter(tmpFileName));
String line;
Scanner read = new Scanner(System.in);
System.out.println("Please Enter Username");
String UserN = read.nextLine();
System.out.println("Please Enter Chips to Add");
String UserCadd = read.nextLine();
while ((line = br.readLine()) != null) {
String[] details = line.split("\\|");
String Username = details[0];
String Password = details[1];
String Chips = details[2];
int totalChips = (Integer.parseInt(UserCadd)+ Integer.parseInt(Chips));
if (Username.equals(UserN))
line = Username + "|" + Password + "|" + totalChips;
bw.write("\r\n"+line);
}
bw.close();
br.close();
oldFileName.delete();
tmpFileName.renameTo(oldFileName);
AdminMenu();
} catch (Exception e) {
e.printStackTrace();
return;
} finally {
try {
if(br != null)
br.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(bw != null)
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
new Error
java.lang.ArrayIndexOutOfBoundsException: 1
at testcode.AddChips(testcode.java:53)
at testcode.main(testcode.java:11)