The Java application that I support is logging some details in a flat file. the problem I face some times is that, the entry is very low compared to the previous day. This entry is most essential because our reports are generated based on the file. I went thro code for writing I couldn't figure out any issues. the method which is writing is sync method.
Any suggestions? I can also provide the code for you is you may need?
public synchronized void log (String connID, String hotline, String callerType,
String cli, String lastMenu, String lastInput,
String status, String reason)
{
//String absoluteFP = LOG_LOC + ls + this.getFilename();
//PrintWriter pw = this.getPrintWriter(absoluteFP, true, true);
try
{
pw.print (this.getDateTime ()+ ","+connID +","+hotline+","+callerType+","+ cli+"," + lastMenu + "," + lastInput + "," + status + "," + reason);
//end 1006
pw.print (ls);
pw.flush ();
//pw.close();
}
catch (Exception e)
{
e.printStackTrace ();
return;
}
}
private synchronized PrintWriter getPrintWriter (String absoluteFileName,
boolean append, boolean autoFlush)
{
try
{
//set absolute filepath
File folder = new File (absoluteFileName).getParentFile ();//2009-01-23
File f = new File (absoluteFileName);
if (!folder.exists ())//2009-01-23
{
//System.out.println ("Call Detailed Record folder NOT FOUND! Creating a new);
folder.mkdirs ();
//System.out.println ("Configure log folder");
this.setHiddenFile (LOG_LOC);//set tmp directory to hidden folder
if (!f.exists ())
{
//System.out.println ("Creating a new Call Detailed Record...");//2009-01-23
f.createNewFile ();//2009-01-23
}
}
else
{
if (!f.exists ())
{
//System.out.println ("Creating a new Call Detailed Record...");//2009-01-23
f.createNewFile ();//2009-01-23
}
}
FileOutputStream tempFOS = new FileOutputStream (absoluteFileName, append);
if (tempFOS != null)
{
return new PrintWriter (tempFOS, autoFlush);
}
else
{
return null;
}
}
catch (Exception ex)
{
ex.printStackTrace ();
return null;
}
}
/**
* Set the given absolute file path as a hidden file.
* #param absoluteFile String
*/
private void setHiddenFile (String absoluteFile)
{
//set hidden file
//2009-01-22, KC
Runtime rt = Runtime.getRuntime ();
absoluteFile = absoluteFile.substring (0, absoluteFile.length () - 1);//2009-01-23
try
{
System.out.println (rt.exec ("attrib +H " + "\"" + absoluteFile + "\"").getInputStream ().toString ());
}
catch (IOException e)
{
e.printStackTrace ();
}
}
private String getDateTime ()
{
//2011-076-09, KC-format up to milliseconds to prevent duplicate PK in CDR table.
//return DateUtils.now ("yyyy/MM/dd HH:mm:ss");
return DateUtils.now ("yyyy/MM/dd HH:mm:ss:SSS");
//end 0609
}
private String getFilename ()
{
///return "CDR_" + port + ".dat";//2010-10-01
return port + ".dat";//2010-10-01
}
public void closePW ()
{
if (pw != null)
{
pw.close ();
}
}
You've created a FileOutputStream, but aren't closing that stream. Close that stream and try again. That might be causing the problem.
Messages are getting logged sometime because the garbage collector kicks in at some intervals and closes the FileOutStream. This then allows messages to be logged again. You're getting the unreachable error since you have a return statement in both the if & else blocks. You'll have to take the PrintWriter and FileOutStreamWriter out of the getPrintWriter put it where you usually call the getPrintWriter(). Then you'll be able to close the streams correctly. getPrintWriter should only ensure file exists, so rename it to ensureFileExistance
If you can use Apache Common IO, try this:
public synchronized void log(String connID, String hotline, String callerType,
String cli, String lastMenu, String lastInput,
String status, String reason) {
String absoluteFP = LOG_LOC + ls + this.getFilename();
File file = new File(absoluteFP);
String message = this.getDateTime() + "," + connID + "," + hotline + "," + callerType + "," + cli + "," + lastMenu + "," + lastInput + "," + status + "," + reason;
try {
// note that you must explicitly add new line character if you want the line to end with newline
FileUtils.write(file, message + "\n", "UTF-8", true);
} catch (IOException ex) {
ex.printStackTrace ();
}
}
In Common IO 2.1, you can append a file that you are writting to. You can now get rid of the closePW and getPrintwriter and since the log method is synchronized, the file can be written one at a time from the same object. However, if you try to write the same file from different object at the same time, you will end up having overwritting problem.
Also, Common IO create the missing parent folder for you automatically. There is no need to explicitly check and create the folder.
Related
I am trying to write a method which recursively gathers data from files, and writes erroneous data to an error file. See code block:
public static LinkedQueue<Stock> getStockData(LinkedQueue<Stock> stockQueue, String startPath) throws Exception {
File dir = new File(getValidDirectory(startPath));
try (PrintStream recordErrors = new PrintStream(new File("EODdataERRORS.txt"))) {
for (File name : dir.listFiles()) {
if (name.isDirectory()) {
getStockData(stockQueue, name.getPath());
}
else if (name.canRead()) {
Scanner readFile = new Scanner(name);
readFile.nextLine();
while (readFile.hasNext()) {
String line = readFile.nextLine();
String[] lineArray = line.split(",+");
if (lineArray.length == 8) {
try {
Stock stock = new Stock(name.getName().replaceAll("_+(.*)", ""));
stock.fromRecord(lineArray);
stockQueue.enqueue(stock);
}
catch (Exception ex) {
recordErrors.println(line + " ERROR: " + ex.getMessage());
System.err.println(line + " ERROR: " + ex.getMessage());
}
}
else {
recordErrors.println(line + " ERROR: Invalid record length.");
System.err.println(line + " ERROR: Invalid record length.");
}
}
}
}
}
catch (FileNotFoundException ex) {
System.err.println("FileNotFoundException. Please ensure the directory is configured properly.");
}
return stockQueue;
}
However, the error file is always blank.
I've tried calling the .flush() and .close() methods. System.err is outputting so I know the code is being run. I've tried instantiating the PrintStream outside of the try-with-resources, no change.
I've tried calling the method at earlier points in the code (i.e. right after instantiation of the printStream, and in the if{} block) and it does output to the error file. It's only within the catch{} and else{} blocks (where I actually need it to work) that it refuses to print anything. I've also tried storing the error data and using a loop after the blocks to print the data and it still won't work. See code block:
public static LinkedQueue<Stock> getStockData(LinkedQueue<Stock> stockQueue, String startPath) throws Exception {
File dir = new File(getValidDirectory(startPath));
LinkedQueue errors = new LinkedQueue();
try (PrintStream recordErrors = new PrintStream(new File("EODdataERRORS.txt"))) {
for (File name : dir.listFiles()) {
if (name.isDirectory()) {
getStockData(stockQueue, name.getPath());
}
else if (name.canRead()) {
Scanner readFile = new Scanner(name);
readFile.nextLine();
while (readFile.hasNext()) {
String line = readFile.nextLine();
String[] lineArray = line.split(",+");
if (lineArray.length == 8) {
try {
Stock stock = new Stock(name.getName().replaceAll("_+(.*)", ""));
stock.fromRecord(lineArray);
stockQueue.enqueue(stock);
}
catch (Exception ex) {
errors.enqueue(line + " ERROR: " + ex.getMessage());
System.err.println(line + " ERROR: " + ex.getMessage());
}
}
else {
errors.enqueue(line + " ERROR: Invalid record length.");
System.err.println(line + " ERROR: Invalid record length.");
}
}
}
}
while (!errors.isEmpty()) {
recordErrors.println(errors.dequeue());
}
}
catch (FileNotFoundException ex) {
System.err.println("FileNotFoundException. Please ensure the directory is configured properly.");
}
return stockQueue;
}
Edit
Code has been edited to show instantiation of the PrintStream only once. The error persists. I am sorry there is no Repex, I cannot recreate this error except for in this specific case.
I have solved the issue. I'm not really sure what the issue was, but it appears to have something to do with the PrintStream being instantiated in a method other than the main{} method. This would also explain why I was unable to recreate this error, try as I might.
As such, I've solved it by simply storing the errors in a list and printing them in the main{} method.
public static void getStockData(LinkedQueue<Stock> stockQueue, LinkedQueue<String> errorQueue, String startPath) {
File dir = new File(getValidDirectory(startPath));
try {
for (File name : dir.listFiles()) {
if (name.isDirectory()) {
getStockData(stockQueue, errorQueue, name.getPath());
}
else if (name.canRead()) {
Scanner readFile = new Scanner(name);
readFile.nextLine();
while (readFile.hasNext()) {
String line = readFile.nextLine();
String[] lineArray = line.split(",+");
if (lineArray.length == 8) {
try {
Stock stock = new Stock(name.getName().replaceAll("_+(.*)", ""));
stock.fromRecord(lineArray);
stockQueue.enqueue(stock);
}
catch (Exception ex) {
errorQueue.enqueue(line + "; ERROR: " + ex.getMessage());
System.err.println(line + "; ERROR: " + ex.getMessage());
}
}
else {
errorQueue.enqueue(line + "; ERROR: Invalid record length.");
System.err.println(line + "; ERROR: Invalid record length.");
}
}
}
}
}
catch (FileNotFoundException ex) {
System.err.println("FileNotFoundException. Please ensure the directory is configured properly.");
}
}
This has the downside of taking up more memory, but I see no other way to get this to work the way I want it to. Thanks for the help!
I have a simple program that reads in commands and performs them. Rightnow I have this code for inserting certain text into a text file:
Example command:
INSERT "John Smith" INTO college.student
My main method:
else if(command.substring(0,6).equalsIgnoreCase("INSERT")){
String string = command.substring(7, command.indexOf("INTO") - 1);
String DBNameTBName = command.substring(command.indexOf("INTO") + 5);
String tableName = DBNameTBName.substring(DBNameTBName.indexOf(".") + 1);
String DBName = DBNameTBName.substring(0, DBNameTBName.indexOf("."));
if(DBCommands.insert(string, DBName, tableName)){
statfileWriter.println("Inserted " + string + " into table " + tableName + " in " + DBName);
statfileWriter.println("(" + command + ")");
statfileWriter.flush();
}
else{
errfileWriter.println("Error: Could not insert " + string + " into table " + tableName + " in " + DBName);
errfileWriter.println("(" + command + ")");
errfileWriter.flush();
}
And the insert method it calls:
public static boolean insert(String string, String DBName, String tableName){
try{
string = string.substring(string.indexOf('"') + 1, string.lastIndexOf('"')); //removes quotes
File tableToWriteTo = new File(DBName + "/" + tableName + ".txt");
if (!tableToWriteTo.exists()){
return false;
}
PrintWriter writer = new PrintWriter(new FileWriter
(tableToWriteTo, true));
writer.println(string);
writer.close();
return true;
}
catch(Exception e){
return false;
}
}
I am getting very weird behavior with my insert method. It returns true as it always prints to my status log and not error log. I know the method to create the .txt file is working perfectly, I have tested it many times and the student.txt file is always there. With my insert command, if I change the File = new File line to this:
File tableToWriteTo = new File(tableName + ".txt");
Then it unsurprisingly creates a .txt file called "student" with my example command, but not in the "DBName" folder. If I change it to this:
File tableToWriteTo = new File(DBName + "/" + tableName);
Then it creates a file called "student" with no type (as in, Windows asks what I want to open it with) but puts in the string I want to insert into it. I should note that if there are multiple INSERT commands then it writes all the strings as I would like it to.
I have tried declaring PrintWriter and File in my main method and passing them in, but that doesn't work either.
How can I get it to write into students.txt in the directory college?
EDIT: Oh my goodness, I'm the stupidest person on Earth. I didn't look at the full commands list I received for this assignment and I forgot there was a delete command and they were BOTH working. I would delete this question but I'll leave this up in case anyone in the future wants to see an example of FileWriter.
I changed the if condition in the insert method. The file is not expected to exist. So ideally the condition should not be negated. I used the following code and it is working for me.
public class InsertToWriteTo {
public static void main(String[] args) {
boolean ret = insert("\"hello\"", "college", "student");
System.out.println(ret);
}
public static boolean insert(String string, String DBName, String tableName) {
try {
string = string.substring(string.indexOf('"') + 1, string.lastIndexOf('"')); // removes quotes
File tableToWriteTo = new File(DBName + "/" + tableName + ".txt");
if (tableToWriteTo.exists()) { // changed condition
System.out.println("File exists");
return false;
}
PrintWriter writer = new PrintWriter(new FileWriter(tableToWriteTo, true));
writer.println(string);
writer.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
Hope this helps!
I have n number of thread getting created at run time according to the input source files present in a folder. For every thread, I have one common class which has all the functions present that are used by every thread. Every thing is working perfectly except the part where batch files are run.
I have main class which is creating thread(which is working perfectly fine). Then I am creating batch files with relevant contents( which is also running perfectly). After that, only 1(can be anyone, no specific pattern) thread is able to execute the batch file and not the others.
Code:
String batch_content = "echo off \n "
+ "powershell.exe -file "
+ utility_path + "convertCSVSwiss.ps1 " + fpath + filename + " -executionpolicy Unrestricted \n ";
String batch_name = "batch_" + fname +"_"+sdf.format(cal.getTime())+ ".bat";
Utils.createBatchFile(batch_content, bat_file_path, batch_name);
Utils.RunBatch(bat_file_path, batch_name,csv_file_path,fname);
Utils.createBatchFile is working fine which create a batch file with the batch content. But Utils.RunBatch seems to having some problem. Here is the code for RunBatch:
public static void RunBatch(String filepath, String filename,String csv_file_path,String fname) throws Exception {
try {
System.out.println("Started Program");
new File(csv_file_path + "\\" + fname).mkdir();
String filePath1 = filepath + filename;
System.out.println("Batch file running is " + filePath1);
Process p = Runtime.getRuntime().exec(new String[] { "cmd.exe", "/c", filePath1 });
p.getOutputStream().close();
p.waitFor();
} catch (Exception e) {
e.printStackTrace();
}
}
My log file prints this:
Batch file running is C:\ER\ETL\bat files\batch_Sample_Data_10_40_16_12_40_37.bat
Batch file running is C:\ER\ETL\bat files\batch_ssd_10_40_16_12_40_37.bat
but it runs only the first one.
Any help would be appreciated.
P.S I am sorry if I missed any information that may be necessary to get this problem resolved. Please let me know and I can then edit my post.
EDIT:
Here is my code.
//main class to start new thread for every excel file present in the source directory
public class LoadData{
public static void main(String[] args) throws Exception{
try{
File folder = new File(fpath);
File[] listoffiles = folder.listFiles();
for (int i = 0; i < listoffiles.length; i++) {
if (listoffiles[i].isFile()) {
filename = listoffiles[i].getName();
c = filename.lastIndexOf(".");
absfilename = filename.substring(0, c);
System.out.println("File name with extension is "+filename);
System.out.println("File name is "+absfilename);
System.out.println("Starting thread for "+absfilename);
ConvertToCSV et = new ConvertToCSV();
et.fpath = fpath;
et.utility_path=utility_path;
et.filename=filename;
et.fname = absfilename;
et.bat_file_path =bat_file_path;
et.tpath =tpath;
et.csv_file_path=csv_file_path;
Thread t = new Thread(et);
t.start();
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
//class to create the batch file content
public class ConvertToCSV implements Runnable{
String fpath,utility_path,filename,fname,bat_file_path,tpath,csv_file_path;
try{
String batch_content = "echo off \n "
+ "powershell.exe -file "
+ path_to_powershell_script_to_convert_excel_into_csv + "convertCSVSwiss.ps1 " + path_and_name_to_the_excel_file " -executionpolicy Unrestricted \n ";
String batch_name = "batch_" + excel_file_name +"_"+sdf.format(cal.getTime())+ ".bat";
Utils.createBatchFile(batch_content, bat_file_path, batch_name);
Utils.RunBatch(bat_file_path, batch_name,csv_file_path,fname);
}
catch (Exception e) {
e.printStackTrace();
}
}
public class Utils{
//function to create the batch file
public static void createBatchFile(String batch_content, String path, String batch_name) throws IOException {
String p = path + batch_name;
File batfile = new File(p);
FileWriter fw = new FileWriter(batfile);
fw.write(batch_content);
fw.close();
}
//function to run the batch file
public static void RunBatch(String filepath, String filename,String csv_file_path,String fname) throws Exception {
try {
System.out.println("Started Program");
new File(csv_file_path + "\\" + fname).mkdir();
String filePath1 = filepath + filename;
System.out.println("Batch file running is " + filePath1);
Process p = Runtime.getRuntime().exec(new String[] { "cmd.exe", "/c", filePath1 });
p.getOutputStream().close();
p.waitFor();
} catch (Exception e) {
e.printStackTrace();
}
}
}
EDIT2: I have added the run for ConvertTO CSV. My code is doing say 10 things, and 9 of them are working fine except running two batch files with different names from the same folder
public class ConvertToCSV implements Runnable{
String fpath,utility_path,filename,fname,bat_file_path,tpath,csv_file_path,pg_db_url,pg_db,pg_db_uid,pg_db_pwd,plpgsql_path,Log_Path;
SimpleDateFormat sdf = new SimpleDateFormat("dd_mm_yy_hh_mm_ss");
Calendar cal = Calendar.getInstance();
#Override
public void run() {
try {
runConvertToCSV(fpath,utility_path,filename,fname,bat_file_path,tpath,csv_file_path,plpgsql_path);
} catch (Exception e) {
e.printStackTrace();
}
}
private void runConvertToCSV(String fpath,String utility_path,String filename,String fname,String bat_file,String tpath,String csv_file_path,String plpgsql_path) throws Exception{try{
String batch_content = "echo off \n "
+ "powershell.exe -file "
+ path_to_powershell_script_to_convert_excel_into_csv + "convertCSVSwiss.ps1 " + path_and_name_to_the_excel_file " -executionpolicy Unrestricted \n ";
String batch_name = "batch_" + excel_file_name +"_"+sdf.format(cal.getTime())+ ".bat";
Utils.createBatchFile(batch_content, bat_file_path, batch_name);
Utils.RunBatch(bat_file_path, batch_name,csv_file_path,fname);
}
catch (Exception e) {
e.printStackTrace();
}
}
EDIT3#:
My guess was that maybe because all the batch files are trying to access the same powershell script, that is why it is not working. But then i created ps script for every batch file. Also, added error stream to the stdout to check if there is any error and this is what i am getting:
Standard Error:
The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
At C:\ER\ETL\ETL_SOURCE\convertCSVSwiss_Swiss_Sample_Data.ps1:24 char:2
+ $Worksheet.SaveAs($ExtractedFileName,6)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
there are number of same error at different line. NOTE: It is the same ps script for all the batch files, it runs only for one and not for others. and that one can be anyone(no pattern).
If i run the above batch file manually, then it succeeds.
I am trying to get this JTextArea, called textArea, to update while it is copying these photos but I can't quite seem to get it to work. I was using this code:
String name = "";
int numberOfPicturesCopied = 0;
while (pictures.isEmpty() == f) {
try {
File tmp = pictures.firstElement();
name = tmp.getName();
String filename = destination + Meta.date(tmp) + tmp.getName();
Path source = tmp.toPath();
File destFile = new File(filename);
Path destination = destFile.toPath();
Files.copy(source, destination,
StandardCopyOption.COPY_ATTRIBUTES);
textArea.append("Copied " + name + "\n");
pictures.removeElementAt(0);
numberOfPicturesCopied++;
} catch (FileAlreadyExistsException faee) {
textArea.append("Skipped " + name
+ ": Picture Already In Computer\n");
} catch (NoSuchFileException ncfe) {
File tmp = pictures.firstElement();
String filename = destination + Meta.date(tmp);
File newDir = new File(filename);
newDir.mkdir();
} catch (IOException ee) {
// TODO Auto-generated catch block
ee.printStackTrace();
}
}
and then I changed it to this:
public void copyPictures(){
SwingUtilities.invokeLater(new Thread(){
public void run(){
String name = "";
while(pictures.isEmpty() == f){
try {
File tmp = pictures.firstElement();
name = tmp.getName();
String filename = destination + Meta.date(tmp) + tmp.getName();
Path source = tmp.toPath();
File destFile = new File(filename);
Path destination = destFile.toPath();
Files.copy(source, destination, StandardCopyOption.COPY_ATTRIBUTES);
textArea.append("Copied " + name + "\n");
pictures.removeElementAt(0);
numberOfPicturesCopied++;
} catch(FileAlreadyExistsException faee){
textArea.append("Skipped " + name +": Picture Already In Computer\n");
} catch (NoSuchFileException ncfe){
File tmp = pictures.firstElement();
String filename = destination + Meta.date(tmp);
File newDir = new File(filename);
newDir.mkdir();
} catch (IOException ee) {
// TODO Auto-generated catch block
ee.printStackTrace();
}
}
}
});
}
with the same outcome. Any suggestions?
Also, is there any way to get the text to come in at the top of text area?
How to insert your text at the start is already answered. The other part of your question is the same as always ... you are performing heavy work on the Event Dispatch Thread, which is no longer able to perform repaints.
What you should do is perform the heavy work on a worker thread, and only update the UI on the EDT. You can for example use a SwingWorker, which is designed for this. Or even simpler, take your current code and with a few simple modifications
public void copyPictures(){
new Thread(){
public void run(){
while(pictures.isEmpty() == f){
try {
File tmp = pictures.firstElement();
final String name = tmp.getName();
String filename = destination + Meta.date(tmp) + tmp.getName();
Path source = tmp.toPath();
File destFile = new File(filename);
Path destination = destFile.toPath();
Files.copy(source, destination, StandardCopyOption.COPY_ATTRIBUTES);
SwingUtilities.invokeLater(
new Runnable(){
public void run(){
textArea.append("Copied " + name + "\n");
}
}
);
pictures.removeElementAt(0);
numberOfPicturesCopied++;
} catch(FileAlreadyExistsException faee){
textArea.append("Skipped " + name +": Picture Already In Computer\n");
} catch (NoSuchFileException ncfe){
File tmp = pictures.firstElement();
String filename = destination + Meta.date(tmp);
File newDir = new File(filename);
newDir.mkdir();
} catch (IOException ee) {
// TODO Auto-generated catch block
ee.printStackTrace();
}
}
}
}.run();
}
See how the work is done on a separate Thread yet the UI is updated on the EDT. More information can be found in the Swing Concurrency tutorial or on SO (keyword for your search is SwingWorker, which will results in a heap of examples as this is a daily question)
Not sure what you are asking, the title seems to be saying that the text isnt updating, but your question seems to indicate that is isnt being inserted where you want it to be...
If its the latter, use the insert method instead
textArea.insert("Copied " + name + "\n",0);
to put it at the top of the text area.
Could you please suggest how to deal with these situations ? I understand that in the second example, it is very rare that it would happen on unix, is it ? If access rights are alright. Also the file wouldn't be even created. I don't understand why the IOException is there, either it is created or not, why do we have to bother with IOException ?
But in the first example, there will be a corrupted zombie file. Now if you tell the user to upload it again, the same thing may happen. If you can't do that, and the inputstream has no marker. You loose your data ? I really don't like how this is done in Java, I hope the new IO in Java 7 is better
Is it usual to delete it
public void inputStreamToFile(InputStream in, File file) throws SystemException {
OutputStream out;
try {
out = new FileOutputStream(file);
} catch (FileNotFoundException e) {
throw new SystemException("Temporary file created : " + file.getAbsolutePath() + " but not found to be populated", e);
}
boolean fileCorrupted = false;
int read = 0;
byte[] bytes = new byte[1024];
try {
while ((read = in.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
} catch (IOException e) {
fileCorrupted = true;
logger.fatal("IO went wrong for file : " + file.getAbsolutePath(), e);
} finally {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
if(fileCorrupted) {
???
}
}
}
public File createTempFile(String fileId, String ext, String root) throws SystemException {
String fileName = fileId + "." + ext;
File dir = new File(root);
if (!dir.exists()) {
if (!dir.mkdirs())
throw new SystemException("Directory " + dir.getAbsolutePath() + " already exists most probably");
}
File file = new File(dir, fileName);
boolean fileCreated = false;
boolean fileCorrupted = false;
try {
fileCreated = file.createNewFile();
} catch (IOException e) {
fileCorrupted = true;
logger.error("Temp file " + file.getAbsolutePath() + " creation fail", e);
} finally {
if (fileCreated)
return file;
else if (!fileCreated && !fileCorrupted)
throw new SystemException("File " + file.getAbsolutePath() + " already exists most probably");
else if (!fileCreated && fileCorrupted) {
}
}
}
I really don't like how this is done in Java, I hope the new IO in Java 7 is better
I'm not sure how Java is different than any other programming language/environment in the way you are using it:
a client sends some data to your over the wire
as you read it, you write it to a local file
Regardless of the language/tools/environment, it's possible for the connection to be interrupted or lost, for the client to go away, for the disk to die, or for any other error to occur. I/O errors can occur in any and all environments.
What you can do in this situation is highly dependent on the situation and the error that occured. For example, is the data structured in some way where you could ask the user to resume uploading from record 1000, for example? However, there is no single solution that fits all here.