How to save a file without overriding the existing with same name - java

I am trying to save a file as *.xlsx without overwriting the existing file with the same name. I thought to add number suffixes to new file names, like file(1).xlsx, file(2).xlsx in case only if the specified file exists. Here what I have tried so far:
do {
s = JOptionPane.showInputDialog("Enter the name of the file name");
File tmpDir = new File(System.getProperty("user.home"), "Documents\\Challan_Reports\\" + s + ".xlsx");
boolean exists = tmpDir.exists();
if (exists) {
JOptionPane.showMessageDialog(this, "File Name Already exists try again!");
}
else {
break;
}
} while (true);
if (s.equals("") || s.equals(null)) {
//.........................................................................
File tmpDir = new File(System.getProperty("user.home"), "Documents\\Challan_Reports\\" + gname + " " + date + ".xlsx");
boolean exists = tmpDir.exists();
if (exists) {
JOptionPane.showMessageDialog(this, "exists 1");
for (int m= 1; true;m++)
{
JOptionPane.showMessageDialog(this, "exists m " + m);
File tmpDir1 = new File(System.getProperty("user.home") + "\\Documents\\Challan_Reports\\" + gname + " " + date + " (" + m + ").xlsx");
System.out.println(System.getProperty("user.home") + "\\Documents\\Challan_Reports\\" + gname + " " + date + " (" + m + ").xlsx");
boolean exists1 = tmpDir1.exists();
if (exists) {
System.out.println("exists file");
continue;
}
else {
System.out.println(" not exists");
filename = System.getProperty("user.home") + "\\Documents\\Challan_Reports\\" + gname + " " + date + " (" + m + ").xlsx";
break;
}
}
}
// FileOutputStream out = new FileOutputStream(new File(System.getProperty("user.home"),"Documents\\Challan_Reports\\"+gname+" "+date+".xlsx"));
// workbook.write(out);
// out.close();
}
FileOutputStream out = new FileOutputStream(new File(filename));
workbook.write(out);
out.close();
System.out.println(
"Writesheet.xlsx written successfully");
JOptionPane.showMessageDialog(this, filename + ".xlsx \n\\Generated at path" + System.getProperty("user.home") + "\\Documents\\Challan_Reports");
}
catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
}
The problem is that it gives the output as the file(1) or file(2)..... exists
when it doesn't. If condition in the loop works only the first time if I put the condition as if(!exists). Please help me out.

You are doing check mistake, instead checking for variable exists1 , you are checking exists and that is true from before for loop part.
try changing as below.
boolean exists1 = tmpDir1.exists();
if(exists1)// change here exists to exists1
{
System.out.println("exists file");
continue;
}
else{
System.out.println(" not exists");
filename=System.getProperty("user.home")+"\\Documents\\Challan_Reports\\"+gname+" "+date+" ("+m+").xlsx";
break;
}

In the condition where you are checking the file existence you are not doing anything right? Not appending anything in name hence if file exists, it will go ahead and try to save only the same name. Please try to append once you found the file existence

Related

How do I read data from file (with specific condition) and display the information on the screen

vaccination.txt
Can someone help me with my codes? I have a problem displaying the information on the screen. I need to display the info based on the question requirement below:
Display all information about those born in Selangor who received the booster dose (dose 3) on screen. The person born in Selangor is represented by two digits there are 10 after the six digits that represent the birth date from the identification (ic) number.
I also have a problem writing the data into the relevant files. I tried the same method (by using the print writer) as what I have done before, but it doesn't work here and Idk why. Do help me
import java.io.*;
import java.util.*;
public class Main
{
public static void main(String\[\] args) {
File inFile = new File ("vaccination.txt");
File comorbid = new File ("comorbid.txt");
File nonComorbid = new File ("non_comorbid.txt");
try {
//read data from file
Scanner sc = new Scanner (inFile);
//write data into file
PrintWriter pw = new PrintWriter(comorbid);
PrintWriter pw2 = new PrintWriter (nonComorbid);
String vaccinePlace = " ", ICnum = " ", category = " ", vaccineType = " ";
int doseNum = 0;
pw.println("Matric Name Part Gender");
pw.println("--------------------------------------------------------------------");
pw2.println("Matric Name Part Gender");
pw2.println("--------------------------------------------------------------------");
while(sc.hasNext()) //check line by line
{
String data = sc.nextLine();
StringTokenizer st = new StringTokenizer(data, ":");
vaccinePlace = st.nextToken();
ICnum = st.nextToken();
category = st.nextToken();
vaccineType = st.nextToken();
doseNum = Integer.parseInt(st.nextToken());
//display information on screen
if (doseNum == 3)
{
if (ICnum.substring(6,8).equalsIgnoreCase("10"))
{
System.out.println("Vaccine place: " + vaccinePlace);
System.out.println("IC number: " + ICnum);
System.out.println("Category: " + category);
System.out.println("Vaccine type: " + vaccineType);
System.out.println("Dose number: " + doseNum);
}
}
//write and store information into comorbid.txt and nonComorbid file
if (category.equalsIgnoreCase("comorbid")) {
pw.println(vaccinePlace + " " + ICnum + " " + vaccineType + " " + doseNum);
}
if (category.equalsIgnoreCase("non-comorbid")) {
pw.println(vaccinePlace + " " + ICnum + " " + vaccineType + " " + doseNum);
}
} //end loop
sc.close();
pw.close();
pw2.close();
}
catch (FileNotFoundException fnf) {
System.out.println(fnf.getMessage());
}
catch (IOException ioe) {
System.out.println(ioe.getMessage());
}
catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}

How to loop writer .csv?

I want every data to be retrieved once looping will occur in the CSV writer, how do I make the loop occur?
thanks!
Data from Firebase
Output writer
*sorry, i can't display images 'cause it must have 10 reputations :(
try {
File root = new File(Environment.getExternalStorageDirectory() + "/StockCount/");
if (!root.exists()) {
root.mkdirs();
}
File myCSV = new File(root, currentDate + " DataStockCount.csv");
myCSV.createNewFile();
FileWriter writer = new FileWriter(myCSV);
writer.append("Date : " + getDate + "\n");
writer.append("Inspector : " + getInspector + "\n");
writer.append("Location : " + getLocation + "\n");
writer.append("Product Name : " + getProductName + "\n");
writer.append("Price : " + getPrice + "\n");
writer.append("Quantity : " + getAmount + "\n");
writer.append("Barcode : " + getCode + "\n");
writer.flush();
writer.close();
Toast.makeText(this, "File Saved Successfully!", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "Error : " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
Why not using an existing library like FastCSV?

public button is always set to false

here's my problem in java, my button is set on public because it is on different window and now i put a function to this button but when I always open the window that the button is included the button is always set to false even the button is clicked it is not functioning.
BTW
veiwTable is a new window:(maybe somebody will laugh to my spelling but I intentionally set it to wrong due to my other variables :) )
convertToTxt is a button
I input else to check if the function is set to false when opening the window
here is my code:
if(veiwTable.convertToTxt.isSelected()) {
try{
File file = new File("e:\\Data Logs\\ " + sn + "_" + status + ".txt");
if(!file.exists()){
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write("Board Name: " + boardName);
bw.newLine();
bw.write("Part Number: " + pn);
bw.newLine();
bw.write("Serial Number: " + sn);
bw.newLine();
bw.write("Board Revision: " + bRev);
bw.newLine();
bw.write("Failing Test Parameter: " + failingTest);
bw.newLine();
bw.write("Failing Checker: " + checker);
bw.newLine();
bw.write("Verified By: " + verifiedBy);
bw.newLine();
bw.write("Remakrs: " + remarks);
bw.newLine();
bw.write("Tester Number: " + testerNumber);
bw.newLine();
bw.write("Datalog:");
bw.newLine();
bw.write(Datalogs );
bw.close();
String note = boardName.concat(" with ").concat(sn).concat(" is located on 'ETS88-spare'\'E:'\'Data Logs'"); //" with " + sn " is located on 'EData Logs'"
JOptionPane.showMessageDialog(null, note);
}catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
}
} else JOptionPane.showMessageDialog(null, "none");
update: my program is now running properly after converting to string all the data on the text box and call it afterwards.
private void convertToTxtActionPerformed(java.awt.event.ActionEvent evt) {
//////not included on the generated datalogs///
String lastDevice = jLastDevice.getText();
String progname = jProgramName.getText();
String progRev = jProgramRevision.getText();
/////////////////////////////////////////////
String boardname = jBoardname.getText();
String pn = jPN.getText();
String sn = jSN.getText();
String boardrev = jBoardRev.getText();
String verifStatus = jVerificationStatus.getText();
String failedTNum = jFailedTNum.getText();
String checker = jFailingChecker.getText();
String tester = jTesterNumber.getText();
String remarks = jRemarks.getText();
String verifiedBy = jVerifiedBy.getText();
String dLogs = jDatalog.getText();
try{
File file = new File("\\\\192.168.1.100\\e\\Data Logs\\ " + sn + "_" + verifStatus + ".txt");
if(!file.exists()){
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write("Board Name : " + boardname);
bw.newLine();
bw.write("Part Number : " + pn);
bw.newLine();
bw.write("Serial Number : " + sn);
bw.newLine();
bw.write("Board Revision : " + boardrev);
bw.newLine();
bw.write("Failing Test Parameter : " + failedTNum);
bw.newLine();
bw.write("Failing Checker : " + checker);
bw.newLine();
bw.write("Verified By : " + verifiedBy);
bw.newLine();
bw.write("Remakrs : " + remarks);
bw.newLine();
bw.write("Tester Number : " + tester);
bw.newLine();
bw.write("Datalog");
bw.newLine();
bw.newLine();
bw.write(dLogs );
bw.close();
String note = boardname.concat(" with ").concat(sn).concat(" is located on 'ETS88-spare'\'E:'\'Data Logs'"); //" with " + sn " is located on 'EData Logs'"
JOptionPane.showMessageDialog(null, note);
//System.out.println(note);
}catch(IOException | HeadlessException e) {
JOptionPane.showMessageDialog(null, e);
}
}

Linux and java: File is being created but text is not written

I am writing a simple terminal program that logs some information, and puts it into a text file that someone can recall on later. Mainly just to have a log of what he person has done. I have been fine in windows, and have not really had this issue, but i fear i am looking over something simple.
Like I said before, if I navigate to the project directory, I see the file has been created, but when I open the file with the text editor, none of the data in the created string is printed.
private static void writeFile( String call,float freq,String mode,int rstSnt,int rstRx,String city, String state) throws IOException{
File fileName = new File("log.txt");
FileOutputStream fos;
try {
fos = new FileOutputStream(fileName);
BufferedWriter write = new BufferedWriter(new OutputStreamWriter(fos));
int i =0;
write.write(i +"; " + call + "; " + freq + "; " + mode + "; " + rstSnt + "; " + rstRx + "; " + city + "," + state + "\n");
i++;
System.out.println("File has been updated!");
} catch (FileNotFoundException ex) {
Logger.getLogger(QtLogger.class.getName()).log(Level.SEVERE, null, ex);
}
}
You need to close the output, or more correctly, you need to code so it will be closed (not necessarily closing it explicitly). Java 7 introduced the try with resources syntax that neatly handles exactly this situation.
Any object that is AutoCloseable can be automatically, and safely, closed using this syntax, like this:
private static void writeFile( String call,float freq,String mode,int rstSnt,int rstRx,String city, String state) throws IOException{
File fileName = new File("log.txt");
try (FileOutputStream fos = = new FileOutputStream(fileName);
BufferedWriter write = new BufferedWriter(new OutputStreamWriter(fos));) {
int i =0;
write.write(i +"; " + call + "; " + freq + "; " + mode + "; " + rstSnt + "; " + rstRx + "; " + city + "," + state + "\n");
i++;
System.out.println("File has been updated!");
} catch (FileNotFoundException ex) {
Logger.getLogger(QtLogger.class.getName()).log(Level.SEVERE, null, ex);
}
}
Just moving the initialization of your closable objects into the try resources block will ensure they are closed, which will flush() them as a consequence of being closed.
After calling the write() function from the BufferedWriter class, you need to call the close() function. You should also call the close() function on your FileOutputStream object.
So your new code should look like this:
private static void writeFile( String call,float freq,String mode,int rstSnt,int rstRx,String city, String state) throws IOException{
File fileName = new File("log.txt");
FileOutputStream fos;
try {
fos = new FileOutputStream(fileName);
BufferedWriter write = new BufferedWriter(new OutputStreamWriter(fos));
int i =0;
write.write(i +"; " + call + "; " + freq + "; " + mode + "; " + rstSnt + "; " + rstRx + "; " + city + "," + state + "\n");
// Close your Writer
write.close();
// Close your OutputStream
fos.close();
i++;
System.out.println("File has been updated!");
} catch (FileNotFoundException ex) {
Logger.getLogger(QtLogger.class.getName()).log(Level.SEVERE, null, ex);
}
}

while loop is only printing one time instead of for the entire loop

I have a program in which I use a while loop to print both to the console and to a html file. However even though it prints to the console the program will only print the final line to the html file. Here is the code for my loop which is supposed to print the information extracted from a text file for the lines 9 to 16.
//read the txt file
Path objPath = Paths.get("dirsize.txt");
if (Files.exists(objPath))
{
File objFile = objPath.toFile();
try(BufferedReader in = new BufferedReader(
new FileReader(objFile)))
{
String line = in.readLine();
int lineNum = 1;
//extract the month
String monthSubstring = line.substring(25,27);
month = Integer.parseInt(monthSubstring) -1 ;
//extact the year
String yearSubstring = line.substring(31,35);
year = (Integer.parseInt(yearSubstring));
//extract the date
String daySubstring = line.substring(28,30);
day = Integer.parseInt(daySubstring);
PrintWriter out = new PrintWriter (new BufferedWriter(new FileWriter("Output.html")));
while(line != null)
{
line = in.readLine();
lineNum ++;
if (lineNum == 3)
{
//extract the hour
String hourSubstring = line.substring(21,23);
hour = Integer.parseInt(hourSubstring);
//extract the minute
String minuteSubstring = line.substring(24,26);
minute = Integer.parseInt(minuteSubstring);
//extract the second
String secondSubstring = line.substring(27,29);
second= Integer.parseInt(secondSubstring);
}
if(lineNum ==5)
{
//Extract the branch
strBranch = line.substring(22, 27);
}
if (lineNum == 6)
{
//Extract the computer
strCPU = line.substring(26,32);
}
if (lineNum >= 9 && lineNum <= 16)
{
//call the MyDirectory methods to get the files name,size and number of files
MyDirectory directory = new MyDirectory(line);
fileName = directory.getName();
fileSize = directory.getsize();
fileNum = directory.getNum();
//create the dteDate calender
GregorianCalendar dteDate = new GregorianCalendar(year, month, day, hour, minute, second);
//fromat the date
SimpleDateFormat strDate = new SimpleDateFormat("MMM dd, yyyy h:m");
//Write the data to the file
out.println((strBranch + "; " +
strCPU + "; " +
strDate.format(dteDate.getTime())) + "; " +
fileName + "; " +
fileSize + "; " +
fileNum);
//create the necessary output for the console
System.out.println((strBranch + "; " +
strCPU + "; " +
strDate.format(dteDate.getTime())) + "; " +
fileName + "; " +
fileSize + "; " +
fileNum);
}
out.flush();
}
}
//catch any IOExceptions and print out e
catch (IOException e)
{
System.out.println(e);
}
}
EDIT: Through advice posted in answers I now have my output for everything but im having a hard time formatting it the html file has all the lines together with no spacing I tried using "\n" at the end of my output but then my code doesn't compile because it says a null is not allowed there anyone know how to format this into lines when it wont let me put "\n" at the end of my print method?
I'm unsure if this is to much code or not enough to solve the problem and if I should add anything to my post or take anything out just let me know.
That's pretty obvious - you create file each time your while loop iterates (see below):
PrintWriter out = new PrintWriter (
new BufferedWriter(
new FileWriter("Output.html")));
//Write the data to the file
out.println((strBranch + "; " +
strCPU + "; " +
strDate.format(dteDate.getTime())) + "; " +
fileName + "; " +
fileSize + "; " +
fileNum);
//flush the data and close the output stream
out.close();
You should create your file before entering while loop instead.
So your code should look something like that:
PrintWriter out = new PrintWriter (new BufferedWriter(new FileWriter("Output.html")));
while(line != null)
{
//perform your file operations here
}
out.close();
---- edit ----
You have updated your code but it's still not ok. You close your file inside of the second loop:
(...)
while (lineNum >= 9 && lineNum <= 16)
{
//call the MyDirectory methods to get the files name,size and number of files
MyDirectory directory = new MyDirectory(line);
fileName = directory.getName();
fileSize = directory.getsize();
fileNum = directory.getNum();
//create the dteDate calender
GregorianCalendar dteDate = new GregorianCalendar(year, month, day, hour, minute, second);
//fromat the date
SimpleDateFormat strDate = new SimpleDateFormat("MMM dd, yyyy h:m");
//Write the data to the file
out.println((strBranch + "; " +
strCPU + "; " +
strDate.format(dteDate.getTime())) + "; " +
fileName + "; " +
fileSize + "; " +
fileNum);
//flush the data and close the output stream
//################# YOU CLOSE YOUR FILE HERE:
out.close();
//create the necessary output for the console
System.out.println((strBranch + "; " +
strCPU + "; " +
strDate.format(dteDate.getTime())) + "; " +
fileName + "; " +
fileSize + "; " +
fileNum);
//move on in the loop so it's not infinte
break;
}
}
When this loop iterates next time you still try to write to your file (and then close it again even though it was closed on previous iteration).
You see only one line in the output file because you are overwriting the file each time you write to it.
If you have to create the PrintWriter within the while(linenum >=9 && linenum <=16) loop, open the file in append mode:
new FileWriter("Output.html", true);
will fix your problem.

Categories