Java BufferedWriter file content is empty [duplicate] - java

This question already has answers here:
Bufferedwriter works, but file empty?
(4 answers)
Closed 6 years ago.
I want to create One file with .cfg extension and content of this file must be in below format
define host {
host_name test.testing.local
alias Server 1
address 192.168.1.111
check_command check-host-alive
max_check_attempts 10
check_interval 5
retry_interval 5
active_checks_enabled 1
passive_checks_enabled 1
check_period 24x7
register 1
}
For this I am using below code
#POST
#Consumes("application/x-www-form-urlencoded")
#Path("/addNewHost")
public Response AddNewHost(String json) {
JSONObject returnJson = new JSONObject();
try {
JSONObject innerJsonObj = new JSONObject(json);
HostObj hostObj = new HostObj();
hostObj.hostname = innerJsonObj.getString("hostname");
hostObj.ipaddress = innerJsonObj.getString("ipaddress");
hostObj.alias = innerJsonObj.getString("alias");
hostObj.check_command = innerJsonObj.getString("check_command");
hostObj.notification_period = innerJsonObj.getString("notification_period");
hostObj.max_check_attempts = innerJsonObj.getInt("max_check_attempts");
hostObj.active_checks_enabled = innerJsonObj.getInt("active_checks_enabled");
hostObj.passive_checks_enabled = innerJsonObj.getInt("passive_checks_enabled");
hostObj.register = innerJsonObj.getBoolean("register");
hostObj.chIntervalInMinutes = innerJsonObj.getInt("chIntervalInMinutes");
hostObj.retryIntervalInMinutes = innerJsonObj.getInt("retryIntervalInMinutes");
hostObj.contact_groups = innerJsonObj.getString("contact_groups");
hostObj.check_period = innerJsonObj.getString("check_period");
String filename = hostObj.ipaddress.replace(".", "");
Properties propFile = LoadProp.getProperties();
BufferedWriter writer = Files.newBufferedWriter(Paths.get(propFile.getProperty(Constants.filepath) + filename + ".cfg"));
writer.write("define host {\n");
writer.write("\thost_name\t" + hostObj.hostname + "\n");
writer.write("\talias\t" + hostObj.alias + "\n");
writer.write("\taddress\t" + hostObj.ipaddress + "\n");
writer.write("\tcheck_command\t" + hostObj.check_command + "\n");
writer.write("\tmax_check_attempts\t" + hostObj.max_check_attempts + "\n");
writer.write("\tcheck_interval\t" + hostObj.chIntervalInMinutes + "\n");
writer.write("\tretry_interval\t" + hostObj.retryIntervalInMinutes + "\n");
writer.write("\tactive_checks_enabled\t" + hostObj.active_checks_enabled + "\n");
writer.write("\tpassive_checks_enabled\t" + hostObj.passive_checks_enabled + "\n");
writer.write("\tcheck_period\t" + hostObj.check_period + "\n");
writer.write("\tregister\t" + hostObj.register + "\n}");
returnJson.put("success", true);
} catch (Exception e) {
JSONObject errorJson = new JSONObject();
errorJson.put("success", false);
errorJson.put("error", errorMsg);
return Response.ok(errorJson.toString()).header("Access-Control-Allow-Origin", "*").build();
}
return Response.ok(returnJson.toString()).header("Access-Control-Allow-Origin", "*").build();
}
But problem is that when I run this, my file is created with empty data.
So please help me to fix this issue.
I am using Java with Eclipse Mars 1.

You need to flush and close the writer by
writer.flush();
writer.close();

Related

Java: Create and write in consecutive files

I'm able correctly to create and to write into a new file, but don't in a second one or more.
What's wrong?
int numbOfFile = 0;
PrintWriter bw = new PrintWriter("C:path\test" + numbOfFile + ".csv");
for (Map.Entry<String, List<Integer>> entry : inSorting.entrySet()) {
String key = entry.getKey();
numbOfFile++;
if (!(numbOfFile % 3 == 0)) {
bw.println(key + " ");
} else {
bw.close();
new PrintWriter(""C:path\test" + numbOfFile + ".csv"");
bw.println(key + " ");
}
}
bw.close();

generating html report using core java but previous result is not storing

My code reading a new file in every 5 sec. From that file I am fetching the status like "pass" and "fail" and writing into a html file. Everything is working fine but my problem is I want previous result also but it is not happening.
Suppose I am reading file1, then I am writing the result in html file and again I read another file2, the result is also writing into same html file. Can anybody please guide me how to do this? I have tried several time but it is not working.
Below is the method where I want to implement the same. If needed I will put the whole code also.
public static String extractText(Reader reader) throws IOException
{
String s[]={
"RAP_45 1",
"RAP_50 1",
"RAP_75 1",
"RAP_PayAsYouGo 1",
"RAP_Refill_Coupon 1",
"RAP_UserPreferences_DefaultMarket 1",
"RAP_NonTransitional_PortIn 1",
"RAP_Transitional_PortIn 1",
"RAP_Activation_Simply_Prepaid_Mexico/Canada 1"
};
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(reader);
FileWriter writeReport = new FileWriter("C:\\Users\\jdutta\\files\\ResultSummary.html");
BufferedWriter bw = new BufferedWriter(writeReport);
String line;
bw.write("<html><Body font=\"14px/1.4 Georgia\" ><br><table border=\"2%\" width=\"50%\"><h3 >Summary:</h3><tr bgcolor=\"black\">");
bw.write("<div border=\"1px solid\" color=\" #ccc\" padding=\"50px\"> <th><font color=\"white\">Test</th> <th><font color=\"white\">Passed</th><th><font color=\"white\">Failed</th> <th><font color=\"white\">Execution time</th>");
while ( (line=br.readLine()) != null)
{
sb.append(line);
}
String textOnly = Jsoup.parse(sb.toString()).text();
int pass=0;
int fail=0;
for(int i=0;i<s.length;i++)
{
String[] s1=s[i].split(" ");
System.out.println("s1.........."+s1[1]);
if(textOnly.contains(s1[0]))
{
if(textOnly.contains(s[i])&&s1[1].equals("1"))
{
System.out.println(s[i]+"pass");
bw.write("<tr><td>" + s1[0] + "</td><td>" + "1" + "</td><td>" + "0" + "</td><td>"+ "200sec" + "</td></tr>");
++pass;
}
else{
System.out.println("fail"+s1[0]);
bw.write("<tr><td>" + s1[0] + "</td><td>" + "0" + "</td><td>" + "1" + "</td><td>"+ "200sec" + "</td></tr>");
++fail;
}
}
else{
bw.write("<tr><td>" + s1[0] + "</td><td>" + "-" + "</td><td>" + "-" + "</td><td>"+ "-" + "</td></tr>");
}
}
bw.write("<tr><th>" + "Total" + "</th><th>" + pass + "</th><th>" + fail + "</th></tr>");
bw.write("</tr></table></Body></html>");
bw.close();
return textOnly;
}
}
Thanks in advance.
You need to change the way you initiate FileWritter to append, like so:
String htmlFilePath = "C:\\Users\\jdutta\\files\\ResultSummary.html";
File htmlFile = new File(filePathString);
boolean append = htmlFile.isFile() && htmlFile.exists();
FileWriter writeReport = new FileWriter(htmlFilePath, append); //notice append
//I assume you dont need to append html header to existing file
if (!append) {
bw.write("<html><Body font=\"14px/1.4 Georgia\" ><br><table border=\"2%\" width=\"50%\"><h3 >Summary:</h3><tr bgcolor=\"black\">");
}

Request parameters coming from jsps are changed when two different users access the code same time

public String generateDataPDF() {
System.out.println("Inside generate PDF");
String filePath = "";
HttpSession sess = ServletActionContext.getRequest().getSession();
try {
sess.setAttribute("msg", "");
if (getCrnListType().equalsIgnoreCase("F")) {
try {
filePath = getModulePath("CRNLIST_BASE_LOCATION") + File.separator + getCrnFileFileName();
System.out.println("File stored path : " + filePath);
target = new File(filePath);
FileUtils.copyFile(crnFile, target);
} catch (Exception e) {
System.out.println("File path Exception " + e);
}
}
System.out.println("Values from jsp are : 1)Mode of Generation : " + getCrnListType() + " 2)Policy Number : " + getCrnNumber() + " 3)Uploaded File Name : " + getCrnFileFileName() + " 4)LogoType : " + getLogoType()
+ " 5)Output Path : " + getOutputPath() + " 6)Type of Generation : " + getOptionId() + " 7)PDF Name : " + getPdfName());
String srtVAL = "";
String arrayVaue[] = new String[]{getCrnListType(), getCrnListType().equalsIgnoreCase("S") ? getCrnNumber() : filePath, getLogoType().equalsIgnoreCase("WL") ? "0" : "1",
getOutputPath(), getGenMode(), getRenType()};
//INS DB Connection
con = getInsjdbcConnection();
ArrayList selectedCRNList = new ArrayList();
String selectedCRNStr = "";
selectedCRNStr = getSelectedVal(selectedCRNStr, arrayVaue[1]);
String[] fileRes = selectedCRNStr.split("\\,");
if (fileRes[0].equalsIgnoreCase("FAIL")) {
System.out.println("fileRes is FAIL beacause of other extension file.");
sess.setAttribute("pr", "Please upload xls or csv file.");
return SUCCESS;
}
System.out.println("List file is : " + selectedCRNStr);
String st[] = srtVAL.split("[*]");
String billDateStr = DateUtil.getStrDateProc(new Date());
Timestamp strtPasrsingTm = new Timestamp(new Date().getTime());
String minAMPM = DateUtil.getTimeDate(new Date());
String str = "";
String batchID = callSequence();
try {
System.out.println("Inside Multiple policy Generation.");
String userName=sess.getAttribute("loginName").toString();
String list = getProcessesdList(userName);
if (list != null) {
System.out.println("list is not null Users previous data is processing.....");
//setTotalPDFgNERATEDmSG("Data is processing please wait.");
sess.setAttribute("pr","Batch Id "+list+" for User " + userName + " is currently running.Please wait till this Process complete.");
return SUCCESS;
}
String[] policyNo = selectedCRNStr.split("\\,");
int l = 0, f = 0,counter=1;
for (int j = 0; j < policyNo.length; j++,counter++) {
String pdfFileName = "";
int uniqueId=counter;
globUniqueId=uniqueId;
insertData(batchID, new Date(), policyNo[j], getOptionId(), userName,uniqueId);
System.out.println("Executing Proc one by one.");
System.out.println("policyNo[j]" + policyNo[j]);
System.out.println("getOptionId()" + getOptionId());
System.out.println("seqValue i.e batchId : " + batchID);
}
str = callProcedure(policyNo[j], getOptionId(), batchID);
String[] procResponse = str.split("\\|");
for (int i = 0; i < procResponse.length; i++) {
System.out.println("Response is : " + procResponse[i]);
}
if (procResponse[0].equals("SUCCESS")) {
Generator gen = new Generator();
if (getPdfName().equalsIgnoreCase("true")) {
System.out.println("Checkbox is click i.e true");
pdfFileName = procResponse[1];
} else {
System.out.println("Checkbox is not click i.e false");
String POLICY_SCH_GEN_PSS = getDetailsForFileName(userName, policyNo[j], batchID);
String[] fileName = POLICY_SCH_GEN_PSS.split("\\|");
if (getLogoType().equals("0") || getLogoType().equals("2")) {
System.out.println("If logo is O or 1");
pdfFileName = fileName[1];
} else if (getLogoType().equals("1")) {
System.out.println("If logo is 2");
pdfFileName = fileName[0];
}
}
b1 = gen.genStmt(procResponse[1], procResponse[2], "2", getLogoType(), "0", pdfFileName,"1",userName,batchID);
l++;
updateData(uniqueId,batchID, "Y");
} else {
f++;
updateData(uniqueId,batchID, "F");
}
}
sess.setAttribute("pr","Total "+l+" "+getGenericModulePath("PDF_RES1") + " " + " " + getGenericModulePath("PDF_RES2") + " " + f);
}catch (Exception e) {
updateData(globUniqueId,batchID, "F");
System.out.println("Exception in procedure call");
setTotalPDFgNERATEDmSG("Fail");
e.printStackTrace();
sess.setAttribute("pr", "Server Error.");
return SUCCESS;
}
}catch (Exception ex) {
ex.printStackTrace();
sess.setAttribute("pr", "Server Error.");
return SUCCESS;
}
System.out.println("Above second return");
return SUCCESS;
}
GenerateDataPDf method generates PDF based on the parameters i.e ProductType(GenMode),CrnList(uploaded in excel file...)Code works fine when only single user generates PDF. But If two different User(User and roles are assigned in application) start the process same time request paraeters are overridden then! Suppose first user request pdf for 50 customers for product 1. User1's process is still running and second user request for product2. Now User1's pdf are generated but for product2.....! Here batchId is unique for every single request.One table is maintained where batch_id,all pdf,generation flags are mainained there. How do I solve this?
As per your comment, this is what I would do, It's probably not the best way to do !
Firstly : Create a function to collet all your data at the beginning. You should not modify/update/create anything when you are generating a PDF. IE : array/list collectPDFData() wich should retourn an array/list.
Secondly : Use a synchronized methods like synchronized boolean generatePDF(array/list)
"Synchronized" methods use monitor lock or intrinsic lock in order to manage synchronization so when using synchronized, each method share the same monitor of the corresponding object.
NB : If you use Synchronize, it's probably useless to collect all your data in a separate way, but I think it's a good practice to make small function dedicated to a specific task.
Thus, your code should be refactored a little bit.

Data is not in the file created

I have been trying to get data in the file but somehow i am not able to get the data in file, any suggestion is highly appreciated.
File is created as per the requirement, but they are empty.I ahve been trying to fix it by trying various things but it doesnt seem to work.
public class Node {
#SuppressWarnings("unchecked")
public static void main(String[] args) {
// handling the argument and placing it in respective variables for
// further use
int fromNode = 0;
int toNode = 0;
String message = null;
int timeAfter = 0;
// Write a message to the respective node after particular time interval
// to the respective node after
// message example node 2 9 "message" 20 & i.e node x node y the message
// and
for (int i = 0; i < args.length; i++) {
fromNode = Integer.parseInt(args[0]);
toNode = Integer.parseInt(args[1]);
message = args[2];
timeAfter = Integer.parseInt(args[3]);
}
System.out.println("from Node :" + fromNode);
System.out.println("to Node :" + toNode);
System.out.println("message :" + message);
System.out.println("time after which :" + timeAfter);
// ******************************************************************
// opening and closing the file for required appending the content to
// those files
try {
String data = message;
File fileTo = new File(File.separator + "Users"
+ File.separator + "Desktop" + File.separator
+ "Files" + File.separator + "to" + toNode + ".txt");
File fileFrom = new File(File.separator + "Users"
+ File.separator + "Desktop" + File.separator
+ "Files" + File.separator + "from" + fromNode + ".txt");
// if file does not exists, then create it
if (!fileTo.exists()) {
fileTo.createNewFile();
}
if (!fileFrom.exists()) {
fileFrom.createNewFile();
}
// true = append file
FileWriter fileWritter = new FileWriter(fileTo.getName(), true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.write(data);
bufferWritter.flush();
bufferWritter.close();
FileWriter fileWritterfrom = new FileWriter(fileFrom.getName(),
true);
// System.out.println("------>"+data);
BufferedWriter bufferWritterfrom = new BufferedWriter(
fileWritterfrom);
bufferWritterfrom.write(data);
bufferWritterfrom.flush();
bufferWritterfrom.close();
System.out.println("Files have been created");
} catch (IOException e) {
e.printStackTrace();
}
// ******************************************************************
I guess, the files were written, but not at the place you expected. The call fileTo.getName() just gives you the last component of the path. So you wrote to a file with name to<some number>.txt in the current directory.
Try to use just
FileWriter fileWritter = new FileWriter(fileTo, true);
This should write to the file at the full path.
Btw. it is not necessary to create the files first.

Java FTP file get issue

I have a application that runs as a schedule.It connect to ftp server and get files from remote folder.scheduler runs in every 5min time.Sometimes when there are lot of files in remote location, scheduler runs again while first cycle is running.In such situation some times it download 0 size files even actual file size is greater than 0 in remote location.Does anyone have any idea why this happen?
below is the code to import files.
private void importEDIFiles(String host, String user, String password, String path, String road) {
try {
String edi824Path = path + "/" + EDI_824_FOLDER;
FTPBroker ftpBroker = new FTPBroker(host, user, password, edi824Path);
FTPClient client = ftpBroker.makeFTPConeection();
String os = client.getSystemName();
client.setFileTransferMode(FTP.ASCII_FILE_TYPE);
File edi824File = null;
File edi824Filebak = null;
ArrayList<FTPFile> files;
try {
FTPFile[] ftpfiles = client.listFiles();
logger.info("\t" + ftpfiles.length + " files are in ftp location ");
if (ftpfiles.length > 0) {
files = removeZeroFiles(ftpfiles);
for(int x=0;x<files.size();x++){
logger.info("name ---"+files.get(x).getName());
logger.info("size ----"+files.get(x).getSize());
}
String ftpFile = null;
logger.info("\t" + files.size() + " downloading from " + road + " rail road.");
for (int i = 0; i < files.size(); i++) {
ftpFile = files.get(i).getName();
logger.info("\t" + ftpFile + " is downloading....");
// logger.info("\t" + ftpFile + " size ...." + ftpFile.isEmpty());
String source = destinationFilePath + pathSeparator + road + pathSeparator + ftpFile;
String target = edi_824backupFilePath + pathSeparator + road + pathSeparator + ftpFile;
edi824File = new File(source);
edi824Filebak = new File(target);
FileOutputStream fosout = new FileOutputStream(source);
boolean isRetrieved = client.retrieveFile(ftpFile, fosout);
logger.debug("isRetrieved : " + isRetrieved);
FileUtils.copyFile(edi824File,edi824Filebak);
fosout.flush();
fosout.close();
boolean isDelete = client.deleteFile(ftpFile);
logger.debug("isDelete : " + isDelete);
}
} else {
logger.info("No files to Pull in the FTP Location for " + user);
//throw new RuntimeException("No files to Pull in FTP Location.");
}
} catch (Exception e) {
logger.error(e,e);
e.printStackTrace();
} finally {
client.logout();
client.disconnect();
}
} catch (Exception ex) {
logger.error(ex, ex);
ex.printStackTrace();
}
}
you can use a flag boolean isRunning(), setRunning(boolean ), and synchronize your code so that two or more threads would not run the same method at the same time

Categories

Resources