Including an Excel file and call once packed into a jar - java

I have developed an ExcelReader/Writer program that is intended to be ran on other computers. In this program, it takes in an excel.xls of hard data, reads it and writes it in a formatted way to an excel.xlsx file, and then saves it in a directory "CoC-Forms".
To reduce the steps to run my program, I have included the empty .xlsx file that it writes to in the project. However, when exporting it to an executable jar (to run on other computers), I seem to be having trouble accessing this empty form. I know this is probably a very simple answer, but I have been stuck for over a full work day and it has completely halted my progress.
Here is a snippet of my environment. On the left is my Project directory in Intellij (CoC.xlsx is the empty form) and the highlights on the right are where I am attempting to access the file and where the error is happening respectively.
JOptionPane.showMessageDialog(null,"About to look for CoC");
//fileFrom = new File(s + "/out/production/XML Reader/CoC.xlsx");
//fileFrom = new File("/XML Reader/out/production/XML Reader/CoC.xlsx");
//fileFrom = new File("CoC.xlsx");
//fileFrom = new File(ExcelWriter.class.getResource("CoC.xlsx").getPath());
CodeSource src = ExcelWriter.class.getProtectionDomain().getCodeSource();
/*if (src != null) {
URL url = new URL(src.getLocation(), "CoC.xlsx");
fileFrom = new File()
System.out.println(url);
} else {
JOptionPane.showMessageDialog(null,"Failed");
} */
fileFrom = new File(new File("."), "CoC.xlsx");

I solved my problem by having people download the whole project folder, file referencing with a ../../ from point of execution, and then going deeper into the file path to find the location at which I placed the file. Choppy, but it works and solved the problem.

Related

Gradle project and resources folder and logical root for creating files

I have a problem understanding how Intellij is working with a Gradle project and the resources folder.
I have created a default Gradle project its created a module 'group', and a module when looking in the module group the src/main/resources folder shows as a 'resource folder' (however it doesn't in the stand-alone module, where groovy/java/resources are all grey).
So that sort out seems to work when compiling code generally.
I tried however to create a file in Groovy script like this
File newFile = new File ("resources/temp.txt")
def fpath = newFile.toURL()
if (!newFile.exists()) {
println "creating new $fpath file "
newFile.createNewFile()
}
However run you run this it fails at bit like this
creating new file:/D:/Intellij - Azure/quickstart-java/graph/src/main/groovy/playpen/resources/temp.txt file
Caught: java.io.IOException: The system cannot find the path specified
java.io.IOException: The system cannot find the path specified
at java_io_File$createNewFile$1.call(Unknown Source)
at playpen.TinkerPop-Example.run(TinkerPop-Example.groovy:47)
The File seems to have relative root .../src/main/groovy/playpen which is where my script is. there is no src/main/groovy/playpen/resources/ so it fails
if a use File("/resources/temp.txt") and look at the URL it shows asD:\resources\temp.txt` defaulting to same drive as where the script is defined.
If you remove the resources prefix - the file gets created in playpen - again assumed root is same as the source program script.
What I want is to read a file from the 'resources' folder but unless I go to absolute file paths it just ignores the 'resources' folder and only looks in the Groovy source folders.
So for example if I copy the temp.txt into the resources folder and run this
File newFile = new File ("temp.txt")
def fpath = newFile.toURL()
if (!newFile.exists()) {
println "creating new $fpath file "
newFile.createNewFile()
} else {
println "reading file at $fpath"
}
it just creates a new temp.txt in the playpen package where the script runs and doesn't see a copy from 'resources' folder.
So what format of 'file name' do I use so that the 'resources' folder is naturally used to resolve file names - without having to use absolute file names?
Equally if want to create a File programmatically and save that in the 'resources' folder where the script runs from src/main/groovy/playpen, what's the path name that puts it in the correct location.
I'm missing something basic here and can't figure out how to read/or write from the resources folder.
ended up with brute force and ignorance on this one - someone may have a 'smarter'answer, but this one appears to be working. Slightly tweaked some code i got working.
I'm using groovy here rather than java (just less boilerplate noise), and nice File groovy methods
steps -
(1)first locate root of your IDE/project using System.getProperty("user.dir")
(2) get the current resource file for 'this' - the class you run from ide
(3) see if the resource is in $root/out/test/.. dir - it so its a test else its your normal code.
(4) set resourcePath now to correct 'location' either in src/main/resources or src/test/resources/ - then build rest of file from this stub
(5) check if file exists - if so delete and rewrite this (you can make this cleverer)
(6) create file and fill its contents
job done this file should now appear where you expect it. Happy to take cleverer ways to get do this - but for anyone else stuck this seems to do the trick
void exportToFile (dir=null, fileName=null) {
boolean isTest = false
String root = System.getProperty("user.dir")
URL url = this.getClass().getResource("/")
File loc = new File(url.toURI())
String canPath = loc.getCanonicalPath()
String stem = "$root${File.separatorChar}out${File.separatorChar}test"
if (canPath.contains(stem))
isTest = true
String resourcesPath
if (isTest)
resourcesPath = "$root${File.separatorChar}src${File.separatorChar}test${File.separatorChar}resources"
else
resourcesPath = "$root${File.separatorChar}src${File.separatorChar}main${File.separatorChar}resources"
String procDir = dir ?: "some-dir-string"
if (procDir.endsWith("$File.separatorChar"))
procDir = procDir - "$File.separatorChar"
String procFileName = fileName ?: "somedefaultname"
String completeFileName
File exportFile = "$resourcesPath${File.separatorChar}$procDir${File.separatorChar}${procFileName}"
exportFile = new File(completeFileName)
println "path: $procDir, file:$procFileName, full: $completeFileName"
exportFile.with {
if (exists())
delete()
createNewFile()
text = toString()
}
}

Extract Files from Java project, during run proccess

I am trying to extract few files contained in the java project into a certain path, lets say "c:\temp".
I tried to use this example :
String home = getClass().getProtectionDomain().
getCodeSource().getLocation().toString().
substring(6);
JarFile jar = new JarFile(home);
ZipEntry entry = jar.getEntry("mydb.mdb");
File efile = new File(dest, entry.getName());
InputStream in =
new BufferedInputStream(jar.getInputStream(entry));
OutputStream out =
new BufferedOutputStream(new FileOutputStream(efile));
byte[] buffer = new byte[2048];
for (;;) {
int nBytes = in.read(buffer);
if (nBytes <= 0) break;
out.write(buffer, 0, nBytes);
}
out.flush();
out.close();
in.close();
I think I am doing it wrong and, this code probably looking for a specific jar but not in my project directory. I prefer to figure a way that can retrieve my files from resources package, inside the project folder and extract it to specific folder i choose.
I am using Eclipse, 1.4 J2SE library.
Well, it's hard to guess what's wrong without any code examples.
But as for pair of random guesses I could tell that sometimes you get this kind of error when the file is locked by earlier instance of your program which is still running. Make sure you've got only one running instance of Eclipse.
Also you can try to refresh the project folder by right click --> refresh to sync your file system with Eclipse's internal file system: when it comes to Eclipse, multiple refresh/rebuild someway magically solves project problems :)

Where i Can find text file created by servlet in Eclipse

This may be a stupid question, but I have to ask because I couldn't find any proper solution.
I am new to Eclipse. I created a Dynamic Web project in Eclipse, In this, I write a simple code to create a text file, Only file name is specified Not the path that where to create, After successful execution, i could not find my text file in my project folder.
If path is specified in the code, I can find the text file in specified directory, My Question is where i can find my text file if i am not specify a path ?
And my code is
try {
FileWriter outFile = new FileWriter("user_details.txt", true);
PrintWriter out1 = new PrintWriter(outFile);
out1.append(request.getParameter("un"));
out1.println();
out1.append(request.getParameter("pw"));
out1.close();
outFile.close();
System.out.println("file created");
} catch(Exception e) {
System.out.println("error in writing a file"+e);
}
I edited my code with following lines,
String path = new File("user_details.txt").getAbsolutePath();
System.out.println(path);
The path that i got is below
D:\Android\eclipse_JE\eclipse\user_details.txt
Why i got it in the eclipse folder ?
Then,
How can i create a text file in my web app, if this is not the right way to create a textfile ?
The file is located in the actual working directory of your application server. Do a
System.out.println(new File("").getAbsolutPath());
and you'll find the location.
However this is not a good idea to write files in web application like this, because first you never know where it is and second you never know whether you write privilege on it.
You need to specify some filesystem root for your application by passing it as init-parameter and use it as parent for everything you need to do on the filesystem. Check this answer to a similar Question.
You could then create your file like this:
String fsroot = getServletContext().getInitParameter("fsroot")
File ud = new File(fsroot, "user_details.txt");
FileWriter outFile = new FileWriter(ud, true);
You may try the getAbsolutePath() method.
String newFile = new File("Demo.txt").getAbsolutePath();
It will show the location where the files will be created.

Java load external CSV file not working after compiling to Jar

I am writing a Java program using NetBeans that times the process of developing black and white film. One of the options allows you to set the times manually and the other allows you to select the chosen film and developer to calculate the required times from a CSV file that is loaded into an array.
There are 3 files that are loaded, filmdb.csv, masterdb.csv and usersettings.csv. The first two are loaded purely for reading and the third file is loaded and can be written too to save the users default settings.
All 3 files are stored in the project directory and loaded in a similar way to the following code and called from main:
static String[] filmArray;
static int filmRows = 125;
int selectedDevTime;
int tempDevTime;
int minDevTime;
int secDevTime;
public int count = -1;
static void createFilmArray() {
filmArray = new String[filmRows];
Scanner scanLn = null;
int Rowc = 0;
int Row = 0;
String InputLine = "";
String filmFileName;
filmFileName = "filmdb.csv";
System.out.println("\n****** Setup Film Array ******");
try {
scanLn = new Scanner(new BufferedReader(new FileReader(filmFileName)));
while (scanLn.hasNextLine()) {
InputLine = scanLn.nextLine();
filmArray [Rowc] = InputLine;
Rowc++;
}
} catch (Exception e) {
System.out.println(e);
}
}
When I press the run button in NetBeans all works well, the files are all loaded and stored to the appropriate array but when I build the file as a .jar the files are not loaded, I have tried copying the 3 files to the same directory as the .jar as well as importing the 3 files into the .jar archive but to no joy.
Is there a specific location where the files should be placed, or should they be imported in a different way?
I would rather not load them from an absolute directory as for example a Windows user may have the files stored in C:\users\somebody\devtimer\file.csv and a Linux user may have the files stored in /home/somebody/devtimer/file.csv.
Cheers
Jim
your files got packaged into the *.jar
once a file is in the jar you cannot accessit as a file using a path (since, if you think about it, its no longer a file. its inside another file, the jar file).
you need to do something like this:
InsputStream csvStream = this.getClass().getResourceAsStream("filmdb.csv");
then you can pass this input stream to your csv parser.
you will not be able to make any modifications to the fhile though. any file you want to change you will need to store outside of your jar.
as for file paths, things like new File("somename") are resolved relative to the current working directory. if you want to know where your root is try something like:
System.err.println(new File(".").getCanonicalPath());
this will be very sensitive to what the working directory was when your application was executed, which in turn depends on how exactly it was executed etc.
If you are running the jar from the same directory the csv files are in then it should be loading. There might be some issue though if you just double click on the jar. You could create a new File represented by the filename and check the absolute path to find out where the jar is running from.
If you want to include the csv inside the jar (cleaner for distribution), you need to load the files in a different way. See this question for a nice example.

Locating default root folder for an Eclipse project

I am reading a file as follows:
File imgLoc = new File("Player.gif");
BufferedImage image = null;
try {
image = ImageIO.read(imgLoc);
}
catch(Exception ex)
{
System.out.println("Image read error");
System.exit(1);
}
return image;
I do not know where to place my file to make the Eclipse IDE, and my project can detect it when I run my code.
Is there a better way of creating a BufferedImage from an image file stored in your project directory?
Take a look in the comments for Class.getResource and Class.getResourceAsStream. These are probably what you really want to use as they will work whether you are running from within the directory of an Eclipse project, or from a JAR file after you package everything up.
You use them along the lines of:
InputStream in = MyClass.class.getResourceAsStream("Player.gif");
In this case, Java would look for the file "Player.gif" next to the MyClass.class file. That is, if the full package/class name is "com.package.MyClass", then Java will look for a file in "[project]/bin/com/package/Player.gif". The comments for getResourceAsStream indicate that if you lead with a slash, i.e. "/Player.gif", then it'll look in the root (i.e. the "bin" directory).
Note that you can drop the file in the "src" directory and Eclipse will automatically copy it to the "bin" directory at build time.
In the run dialog you can choose the directory. The default is the project root.
From my experience it seems to be the containing projects directory by default, but there is a simple way to find out:
System.out.println(new File(".").getAbsolutePath());
Are you trying to write a plugin for Eclipse or is it a regular project?
In the latter case, wouldn't that depend on where the program is installed and executed in the end?
While trying it out and running it from Eclipse, I'd guess that it would find the file in the project workspace. You should be able to find that out by opening the properties dialog for the project, and looking under the Resource entry.
Also, you can add resources to a project by using the Import menu option.
The default root folder for any Eclipse project is also a relative path of that application.
Below are steps I used for my Eclipse 4.8.0 and Java 1.8 project.
I - Place your file you want to interact with along the BIN and SRS folders of your project and not in one of those folders.
II - Implement below code in your main() method.
public static void main(String [] args) throws IOException {
FileReader myFileReader;
BufferedReader myReaderHelper;
try {
String localDir = System.getProperty("user.dir");
myFileReader = new FileReader(localDir + "\\yourFile.fileExtension");
myReaderHelper = new BufferedReader(myFileReader);
if (myReaderHelper.readLine() != null) {
StringTokenizer myTokens =
new StringTokenizer((String)myReaderHelper.readLine(), "," );
System.out.println(myTokens.nextToken().toString()); // - reading first item
}
} catch (FileNotFoundException myFileException) {
myFileException.printStackTrace(); } } // End of main()
III - Implement a loop to iterate through elements of your file if your logic requires this.

Categories