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);
}
}
Related
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());
}
}
}
This is where the data is coming from:
private void btnPlaceOrderActionPerformed(java.awt.event.ActionEvent evt) {
String name = txtClientName.getText();
String address = txtClientAddress.getText();
String date = txtDeliveryDate.getText();
String contact = txtContactInfo.getText();
String small = txtSmall.getText();
String medium = txtMedium.getText();
String large = txtLarge.getText();
BufferedWriter buf;
try{
buf = new BufferedWriter(new FileWriter("orders.txt", true));
buf.write(name + " " + address + " " + small + " " + medium + " " + large + " " + date + " " + contact);
buf.newLine();
buf.close();
JOptionPane.showMessageDialog(this, "Order sent");
} catch (Exception e){
}
}
How would I display the data that gets collected from this into a JTable that updates whenever new data is introduced to the text file?
I am quite new to java, and try as I might, I can't find any examples to help me. I am running ffmpeg as a process and parsing the stderr to get various bits of data - all of which is working fine, but I want to send a "q\n" command to ffmpeg's input from a gui menu item to gracefully quit it whilst it is running when necessary. So all I want to do is send a string programmatically to ffmpeg, the equivalent of sending q return from terminal. Thanks in advance
edit here is the relevant (simplified) section of the code
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { Thread thread = new Thread() {
public void run()
BufferedReader error_reader,input_reader;
InputStreamReader error_isr,input_isr;
String ffmpeg_command = "ffmpeg " + overwrite + " -i " + "\"" + currentfilestring + "\"" + " " + stream + " " + test + " " + findsilence + " " + videocodec + " -b:v " + videoqual + " " + audiocodec + " -ac 2 -ab " + audioqual + " " + res + " " + aspectratio + " " + framerate + " " + "\"" + destdir + destfile + "\"";
System.out.println(ffmpeg_command);
try {
OutputStream stdout;
InputStream stdin;
InputStream stderr;
String errorstr,inputstr;
//Run the ffmpeg
Process ffmpeg = Runtime.getRuntime().exec(ffmpeg_command, null, new File(userDir));
//Get stdin,stderr + stdout
stdin = ffmpeg.getInputStream();
stderr = ffmpeg.getErrorStream();
stdout = ffmpeg.getOutputStream();
stdout.write("\r\n".getBytes());
stdout.flush();
stdout.close();
error_isr = new InputStreamReader(stderr);
error_reader = new BufferedReader(error_isr);
input_reader = new BufferedReader(input_isr);
while (!error_reader.ready()) {
}
while ((errorstr = error_reader.readLine()) != null) {
if(stopconv =="yes"){
//-------------------------------------------------------------------------------------
// TRYING TO INPUT "q\n" TO FFMPEG HERE
//-------------------------------------------------------------------------------------
}
error_isr.close();
error_reader.close();
stdin.close();
stderr.close();
jProgressBar1.setValue(0);
ffmpeg.destroy();
} catch (Exception e) {
e.printStackTrace();
}
};
thread.start();
}
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
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);
}
}