File not found exception, snippet works flawlessly in other projects - file-upload

This following scippet works well, and I have been using it across many projects. However, for this one project, I get a file not found exception.
try {
FileInputStream is = new FileInputStream(file);
String original = file.getName();
Logger.debug("Filename in upload pf %s ", original);
IOUtils.copy(is, new FileOutputStream(Play.getFile(original)));
PfParser p1 = new PfParser();
p1.read(original, month, year);
Payroll.index();
} catch (FileNotFoundException e) {
Logger.error(e, "Exception in uploadSheet: ");
e.printStackTrace();
} catch (IOException e) {
Logger.error(e, "Exception in uploadSheet: ");
e.printStackTrace();
}
This is the read method, where I have tried a few combinations, which are commented out:
FileInputStream myInput = new FileInputStream(
System.getProperty("user.dir") + inputFile);
w = Workbook.getWorkbook(myInput);
// w = Workbook.getWorkbook(new File(inputFile));
// w = Workbook.getWorkbook(new File(System.getProperty("user.dir"),
// inputFile));
This uploads the file to the C:\Program Files (x86)\Apache Software Foundation\Tomcat 6.0\webapps\ROOT\WEB-INF\application folder.
I am trying to read an excel file using Jexcel. The error I get on my server:
java.io.FileNotFoundException: foo.xls (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
Trying the other (commented out) lines, only gives a variation in the error.
java.io.FileNotFoundException: C:\Program Files (x86)\Apache Software Foundation\Tomcat 6.0\foo.xls (The system cannot find the file specified)
I understand its a problem related with absolute and relative paths, but cant seem to find a solution. I do not get any errors, while coding and testing on my local machine which is Ubuntu. Its only when I deploy to a Windows server, do I get these problems.
Thanks.

The FileNotFound exception come when the file is not located on the absolute/relative paths that you provide in your FileInputStream constructor.
FileInputStream is = new FileInputStream(file);
I doubt you are not giving the right location in your FileInputStream constructor. It would be good if you write the complete spinet including file location etc.

I changed the line from
IOUtils.copy(is, new FileOutputStream(Play.getFile(original)));
to
IOUtils.copy(is, new FileOutputStream("./" + original));
Upload now works.

Related

Epplus - Reading through filestream. The process cannot access the file because it is being used by another process. -

I’m having an issue using EPPlus 6.0.6 on the server within an IIS process. I upload an xlsx to the IIS server, then call the method to process the file (read from the file only.) When finished, I want to remove the file from the server folder, but get the error:
The process cannot access the file because it is being used by another process.
Calling method:
Processor processor = new Processor (filename)
{
Await processor.Process();
try { File.Delete(selectedFile); txtStatusMsg += “Cleanup Succeeded”;}
catch (Exception e){ txtStatusMsg += $#"Cleanup Failed - {e.Message}"; }
// error occurs
// ex.message is
// The process cannot access the file because it is being used by another process.
}
The Process method has:
using (FileStream fs =
new FileStream(filename ,
FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (ExcelPackage srcPkg = new ExcelPackage(fs))
{
// read from the file
foreach (ExcelWorksheet srcWs in srcPkg.Workbook.Worksheets) ...
}
}
The file is still locked; I would expect the srcPkg to be disposed after the using block, and fs to be closed/disposed after its using block.
I’ve tried
srcPkg.Dispose();
after the for loop, and
fs.Close();
After the srcPkg using but neither help. Restarting IIS releases the file.
Can i force the file to be unlocked in some way?

how to download exe files in vb.net (Visual Studio 2015)

I try make one program for download one .exe file and run for help in my job.
But idk how to make this, i'm new in VB.
I am using this code, as shown in the Visual Basic document reference:
My.Computer.Network.DownloadFile _
("http://www.cohowinery.com/downloads/WineList.txt", _
"C:\Documents and Settings\All Users\Documents\WineList.txt")
But when I try to download an .exe file, the entire file doesn't complete and I the file is only 1 kb after download.
The webclient should be the way to go a comment above highlights that too.
This is an example from another question:
Either use sync method:
public void DownloadFile()
{
using(var client = new WebClient())
{
client.DownloadFile(new Uri("http://www.FileServerFullOfFiles.net/download/test.exe"), "test.exe");
}
}
Or use new async-await approach:
public async Task DownloadFileAsync()
{
using(var client = new WebClient())
{
await client.DownloadFileTaskAsync(new Uri("http://www.FileServerFullOfFiles.net/download/test.exe"), "test.exe");
}
}
Then call this method like this:
await DownloadFileAsync();
Open up the .exe file you are trying to download in a text editor like NotePad. Odds are what is being downloaded is an HTML page showing some kind of error message like 404 not found.
Another possibility might be that AntiVirus software is moving the original EXE into quarantine and replacing it with a Quarantine MetaData file.
If the file does actually contain binary content your connection could be getting interrupted but odds are if this happened an exception would be thrown.

Velocity Unable To find Resources

This question is already asked but i am trying the same thing that is in accepted answer
protected static final String RESOURCE_LOADER = classpath.resource.loader.class";
static {
System.out.println("Velocity Initialization Started");
velocityEngine = new VelocityEngine();
velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
velocityEngine.setProperty(RESOURCE_LOADER,ClasspathResourceLoader.class.getName());
try {
velocityEngine.init();
} catch (Exception e) {
LOG.error("Failed to load velocity templates e={}", e);
}
}
my velocity file is in
src/main/resources/velocity/templates/command/name.vm
i am getting templates by following command
template = velocityEngine.getTemplate("velocity/templates/command/GenericState.vm");
It works locally but when bundled in jar it does not work , I have examined the jar it consist of velocity folder
i am using velocity to generated java code
I am having maven project setup and maven is creating jar
try this way it should work.
velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "class,file");
velocityEngine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, "org.apache.velocity.runtime.log.Log4JLogChute");
velocityEngine.setProperty("runtime.log.logsystem.log4j.logger", "VELLOGGER");
velocityEngine.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
velocityEngine.setProperty("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.NullLogSystem");
velocityEngine.init();

use beanshell to execute a scripts from a specific folder (error no such file or directory)

I added the library bsh to my android project (jar file), the I create a file executor.bsh under scripts(a folder that I have created under the project)
I used the code below
private final Interpreter i= new Interpreter();
i.source("scripts/executor.bsh");
I got an error:
No such file or directory
Help !!
Interpreter.source(..) looks for a File, where you have a jar entry. However, you can still use it with:
try (Reader script = new InputStreamReader(getClass().getClassLoader().getResourceAsStream("scripts/executor.bsh")) {
Interpreter in = new Interpreter(script, System.in, System.out, System.err, false);
// your script was already loaded
// do something with Interpreter here.
}

Replacing files throws UnauthorizedAccessException in WinRT / Win8

Every once in a while, StorageFiles get locked and I get an UnauthorizedAccessException when trying to overwrite them. I cannot replicate this, it only happens randomly. This is the code for creating files:
using (var stream = new MemoryStream())
{
// ...populate stream with serialized data...
StorageFile file;
Stream fileStream;
try
{
file = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
}
catch (UnauthorizedAccessException ex)
{
Debug.WriteLine("Access denied on file {0}", fileName);
return;
}
fileStream = await file.OpenStreamForWriteAsync();
using (fileStream)
{
stream.Seek(0, SeekOrigin.Begin);
await stream.CopyToAsync(fileStream);
await fileStream.FlushAsync();
}
}
Once a file starts throwing UnauthorizedAccessException, it will always throw it. As if the system has the file locked and I cannot touch it. I have to uninstall the application and rebuild.
When I open the file in my document, I can see that data there. Everything is fine. It was written successfully.
Can anyone see a problem with my code?
Are you saving the file token in the future access list? I ran into this problem when loading files and trying to save updates later. Once I started using the future access list, the problems went away.
http://msdn.microsoft.com/en-us/library/windows/apps/windows.storage.accesscache.storageitemaccesslist
It might be the case when the same file is being accessed from two different points in the code at the same time.