Writing to .txt skipping lines and leaving white spaces java - java

String newPurchaseOrder = dateStr + "#" + customerID + "#" + productCode + "#" + qty;
try {
String filename = "PurchaseOrderDataFile.txt";
FileWriter fw = new FileWriter(filename, true); //the true will append the new data
BufferedWriter bw = new BufferedWriter(fw);
FileReader fr = new FileReader("PurchaseOrderDataFile.txt");
bw.write("\n" + newPurchaseOrder);
bw.close();
} catch (IOException ioe) {
System.err.println("IOException: " + ioe.getMessage());
}
Trying to prevent it from skipping lines when inputting to the .txt file
08/12/13#PMI-1256#DT/9489#8
16/12/13#ENE-5789#PV/5732#25
27/12/13#PEA-4567#PV/5732#3#
09/01/14#PEA-4567#DT/9489#1
16/01/14#EMI-6329#PV/5732#8
16/07/13#ESE-5577#ZR/7413#6
Input skips lines such as above

what do you mean "skipping lines"? bw.write("\n" + newPurchaseOrder); will first put an empty line if that is what you mean, just transfer "\n" to the end.. The following code works fine:
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.FileReader;
import java.io.FileWriter;
class myWrite {
public static void main(String[] args) {
String dateStr = "test";
String customerID = "1";
String productCode = "100";
String qty = "1000";
String newPurchaseOrder = dateStr + "#" + customerID + "#" + productCode + "#" + qty;
String newPurchaseOrder2 = dateStr + "#" + customerID + "#" + productCode + "#" + qty;
try {
String filename = "PurchaseOrderDataFile.txt";
FileWriter fw = new FileWriter(filename, true); //the true will append the new data
BufferedWriter bw = new BufferedWriter(fw);
FileReader fr = new FileReader("PurchaseOrderDataFile.txt");
bw.write(newPurchaseOrder + "\n");
bw.write(newPurchaseOrder2 + "\n");
bw.close();
} catch (IOException ioe) {
System.err.println("IOException: " + ioe.getMessage());
}
}
}
writes:
test#1#100#1000
test#1#100#1000
EDIT: Using the output you told me,
08/12/13#PMI-1256#DT/9489#8
16/12/13#ENE-5789#PV/5732#25
27/12/13#PEA-4567#PV/5732#3#
09/01/14#PEA-4567#DT/9489#1
16/01/14#EMI-6329#PV/5732#8
I then added the line you told me:
16/07/13#ESE-5577#ZR/7413#6
which produces:
08/12/13#PMI-1256#DT/9489#8
16/12/13#ENE-5789#PV/5732#25
27/12/13#PEA-4567#PV/5732#3#
09/01/14#PEA-4567#DT/9489#1
16/01/14#EMI-6329#PV/5732#8
16/07/13#ESE-5577#ZR/7413#6
use my code it works fine and does what you want..

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 get motherboard Serial Number?

For getting the motherboard serial number, I used the following code. The output is empty, however. Is there anything I can do to fix it?
File file = File.createTempFile("realhowto",".vbs");
file.deleteOnExit();
FileWriter fw = new java.io.FileWriter(file);
String vbs =
"Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n"
+ "Set colItems = objWMIService.ExecQuery _ \n"
+ " (\"Select * from Win32_BaseBoard\") \n"
+ "For Each objItem in colItems \n"
+ " Wscript.Echo objItem.SerialNumber \n"
+ " exit for ' do the first cpu only! \n"
+ "Next \n";
fw.write(vbs);
fw.close();
Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
BufferedReader input =
new BufferedReader
(new InputStreamReader(p.getInputStream()));
String line;
while ((line = input.readLine()) != null) {
result += line;
}
if(result.equalEgnoreCase(" ") {
System.out.println("Result is empty");
} else {
System.out.println("Result :>"+result);
}
input.close();
}
I found that the following code works.
package ui;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
public class MB {
public static void main(String[] args) throws IOException {
File file = File.createTempFile("realhowto", ".vbs");
file.deleteOnExit();
FileWriter fw = new java.io.FileWriter(file);
String vbs = "Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n"
+ "Set colItems = objWMIService.ExecQuery _ \n" + " (\"Select * from Win32_BaseBoard\") \n"
+ "For Each objItem in colItems \n" + " Wscript.StdOut.Writeline objItem.SerialNumber \n"
+ " exit for ' do the first cpu only! \n" + "Next \n";
fw.write(vbs);
fw.close();
Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line, result = new String();
while ((line = input.readLine()) != null) {
result += line;
}
if (result.equalsIgnoreCase(" ")) {
System.out.println("Result is empty");
} else {
System.out.println("Result :>" + result);
}
input.close();
}
}

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);
}
}

Help please, while loop and tokenizer and reading files

I need help, obviously. Our assignment is to retrieve a file and categorize it and display it in another file. Last name first name then grade. I am having trouble with getting a loop going because of the error "java.util.NoSuchElementException" This only happens when I change the currently existing while I loop I have. I also have a problem of displaying the result. The result I display is all in one line, which I can't let happen. We are not allowed to use arraylist, just Bufferedreader, scanner, and what i already have. Here is my code so far:
import java.util.;
import java.util.StringTokenizer;
import java.io.;
import javax.swing.*;
import java.text.DecimalFormat;
/*************************************
Program Name: Grade
Name: Dennis Liang
Due Date: 3/31/11
Program Description: Write a program
which reads from a file a list of
students with their Grade. Also display
last name, first name, then grade.
************************************/
import java.util.*;
import java.util.StringTokenizer;
import java.io.*;
import javax.swing.*;
import java.text.DecimalFormat;
class Grade {
public static void main(String [] args)throws IOException {
//declaring
String line = "";
StringTokenizer st;
String delim = " \t\n\r,-";
String token;
String firstname;
String lastname;
String grade;
String S69andbelow="Students with 69 or below\n";
String S70to79 ="Students with 70 to 79\n";
String S80to89= "Students with 80 to 89\n";
String S90to100= "Students with 90 to 100\n";
int gradeint;
double gradeavg = 0;
int count = 0;
File inputFile = new File("input.txt");
File outputFile = new File("output.txt");
FileInputStream finput = new FileInputStream(inputFile);
FileOutputStream foutput = new FileOutputStream(outputFile);
FileReader reader = new FileReader(inputFile);
BufferedReader in = new BufferedReader(reader);
Scanner std = new Scanner(new File("input.txt"));
Scanner scanner = new Scanner(inputFile);
BufferedWriter out = new BufferedWriter(new FileWriter(outputFile));
Scanner scan = new Scanner(S69andbelow);
//reading linev
line = scanner.nextLine();
st = new StringTokenizer(line, delim);
//avoiding selected characters
try {
while(st.hasMoreTokens()) {
firstname = st.nextToken();
lastname = st.nextToken();
grade = st.nextToken();
//storing tokens into their properties
gradeint = Integer.parseInt(grade);
//converting token to int
gradeavg = gradeavg + gradeint;
//calculating avg
count++;
//recording number of entries
if (gradeint <=69) {
S69andbelow = S69andbelow + lastname + " "
+ firstname + " " + "\t" + grade + "\n";
} // saving data by grades
else if (gradeint >= 70 && gradeint <= 79) {
S70to79 = S70to79 + lastname + " " + firstname
+ " " + "\t" + grade + "\n";
} // saving data by grades
else if (gradeint >= 80 && gradeint <=89) {
S80to89 = S80to89 + lastname + " " + firstname
+ " " + "\t" + grade + "\n";
} // saving data by grades
else {
S90to100 = S90to100 + lastname + " " + firstname
+ " " + "\t" + grade + "\n";
} // saving data by grades
}//end while
System.out.println(S69andbelow + "\n" + S70to79 + "\n"
+ S80to89 + "\n" + S90to100);
//caterorizing the grades
gradeavg = gradeavg / count;
//calculating average
DecimalFormat df = new DecimalFormat("#0.00");
out.write("The average grade is: "
+ df.format(gradeavg));
System.out.println("The average grade is: "
+ df.format(gradeavg));
Writer output = null;
output = new BufferedWriter(new FileWriter(outputFile));
// scanner.nextLine(S69andbelow);
//output.write(S69andbelow + "\n" + S70to79 + "\n"
// + S80to89 + "\n" + S90to100);
// output.close();
}
catch( Exception e ) {
System.out.println(e.toString() );
}
// Close the stream
try {
if(std != null )
std.close( );
}
catch( Exception e ) {
System.out.println(e.toString());
}
}
}
my input file looks like this:
Bill Clinton 85 (enter)
Al Gore 100 (enter)
George Bush 95 (enter)
Hillery Clinton 83(enter)
John McCain 72(enter)
Danna Green 87(enter)
Steve Delaney 76(enter)
John Smith(enter)
Beth Bills 60(enter)
It would help to point things out just in case I don't follow you all the way through.
An easy way of finding a problem in this would be to comment out most of the code and find out each step at a time. So start with being able to read the file. Then print to the screen. Then print the organized data to the screen. Finally print the organized data to the file.
This should be a fairly simple

Categories