access File present in classpath servlet - java

In DynamicWebProject - Eclipse, How to get File Object for file present in src folder, i mean to say class path.
Below program works fine but new update to file is present in wtpwebapps, instead i want to get changed in file present in src folder of Eclipse only(How to get FileOutputStream for file present in classpath).
String filename1 = "/WEB-INF/classes/server123.properties";
ServletContext context = req.getSession().getServletContext();
String path1 = context.getRealPath(filename1);
System.out.println("PATH 1 IS :"+path1);
FileInputStream fis1 = new FileInputStream(new File(path1));
int ch1;
while ((ch1 = fis1.read())!=-1) {
System.out.print((char)ch1);
}
fis1.close();
FileOutputStream fos = new FileOutputStream(path1);
fos.write("jayesh".getBytes());
fos.close();

you can use getServletContext()/filename in your code i.e.
properties.load(new FileInputStream(getServletContext().getRealPath("/filename")));
or
properties.load(new FileInputStream(getServletContext().getRealPath(/filename")));

Related

Java creating a file in a certain directory

How do I get a json file I am creating to go into another directory. I am using a method that gives a file name and use this code to create it, its not the full code but Im pretty sure this is the only part I need to modify.
FileInputStream in = new FileInputStream(fileName);
JSONObject obj = new JSONObject(new JSONTokener(in));
right now it puts it in a directory but I want to put it in a folder in that directory.
this also does not work
FileInputStream in = new FileInputStream("/A/Ab/src/serv"+fileName);
///////////////////////////
File cDir = new File("");
FileInputStream in = new FileInputStream(cDir.getAbsoluteFile() +fileName);
Try this:
File dir = new File("/A/Ab/src/serv");
if (!dir.exists()) dir.mkdirs();
then:
FileInputStream in = new FileInputStream("/A/Ab/src/serv/" + filename);`enter code here`
If the directory already exists and you just want to create a new file, then simply do:
FileInputStream in = new FileInputStream(new File("/A/Ab/src/serv/" + filename))

How to get the absolute path of a file in my project (and not of a file stored in a temporary folder)

I am using:
Eclipse Java EE IDE for Web Developers version: Mars.2 Release (4.5.2);
Apache Tomcat v8.0;
a Web Dynamic project;
a Java Servlet.
I have a JSON file stored in the ./WebContent folder. I am trying to get the absolute path of the JSON file in this way:
ServletContext sc = request.getSession().getServletContext();
//String absolutePath = "/Users/kazuhira/Documents/MAC_workspace/lab2_calendario/WebContent/Database/Events.json";
String relativePath = "eventsBackup.json";
String filePath = sc.getRealPath(relativePath);
System.out.println("(saverServlet): the path of the file is "+filePath);
//System.out.println("(saverServlet): the path of the file is "+absolutePath);
//File file = new File(absolutePath);
String content = request.getParameter("jsonEventsArray");
try (FileOutputStream fop = new FileOutputStream(file)) {
System.out.println("(saverServlet): trying to access to the file"+filePath);
// if file doesn't exists, then create it
if (!file.exists()) {
System.out.println("(saverServlet): the file doesn't exists");
file.createNewFile();
System.out.println("(saverServlet): file "+filePath+" created");
}
System.out.println("(saverServlet): writing on the file "+filePath);
// get the content in bytes
byte[] contentInBytes = content.getBytes();
fop.write(contentInBytes);
fop.flush();
fop.close();
System.out.println("(saverServlet): events backup done");
} catch (IOException e) {
e.printStackTrace();
}
and the file path reconstructed from the relativePath is:
/Users/kazuhira/Documents/MAC_workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/lab2_calendario/testJson.txt
Why String filePath = sc.getRealPath(relativePath); generates a path on a temporary folder? In which way I can configure the context on the "real" json file (the same I create in the project)?
I suppose Tomcat is working in a temporary context, why? There's a way to tell him to use the same folder of the project?
Yes, you can by changing an option in your Server configuration in Eclipse
Select the second option in the radio button list :)

Filehandling file path

Basically i have two questions. i am using the below code to read and write z text file.
File myFile = new File("/sdcard/mysdfile.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append("my text here");
myOutWriter.close();
this create a new file every time i want this to OPEN_OR_CREATE(if file already exist don't create a new one)
Ad my second question is that how to change the path "/sdcard/mysdfile.txt" i want this file to stored in my sdcard -> subFolder1 -> SubFolder2
Thnaks
Do not use hardcoded /sdcard or /mnt/sdcard or your app will fail as devices vary on location or mountpoint of that storage. To get the right location use
Environment.getExternalStorageDirectory();
See docs here.
To append content to existing file use new FileOutputStream(myFile, true); instead of just new FileOutputStream(myFile); - see docs on that constructor here.
As for
how to change the path "/sdcard/mysdfile.txt"
Aside from getting rid of /sdcard as said above, just add subfolders to the paths: MyFolder1/MyFolder2/mysdfile.txt. Note these folder have to exists or the path will be invalid. You can always create it by calling myFile.mkdirs().
Replace
FileOutputStream fOut = new FileOutputStream(myFile);
with
FileOutputStream fOut = new FileOutputStream(myFile, true); //true means append mode.
Appart from that I have one suggestion for you.
Never never hardcode /sdcard in code,Rather consider writing.
File myFile = new File(Environment.getExternalStorageDirectory(),"mysdfile.txt");
Try my solution to write to end of text file
private void writeFile (String str){
try {
File f = new File(Environment.getExternalStorageDirectory().toString(),"tasklist.txt");
FileWriter fw = new FileWriter(f, true);
fw.write(str+"\n");
fw.flush();
fw.close();
} catch (Exception e) {
}
}
*File(Environment.getExternalStorageDirectory().toString()+"your/pth/here","tasklist.txt");
File dir = Environment.getExternalStorageDirectory();
File f = new File(dir+"/subFolder1/",xyz.txt); <-- HOW TO USE SUB FOLDER
if(file.exists())
{
// code to APPEND
}
else
{
// code to write new one
}
1> OPEN_OR_CREATE
You can try or can replace MODE_APPEND with true like #Vipul's suggestion
FileOutputStream fOut = openFileOutput(your_path_file, MODE_APPEND);
//it means if the file is exist the content you want write will append into it.
2> stored in my sdcard -> subFolder1 -> SubFolder2
you can use Environment.getExternalStorageDirectory().getAbsolutePath() to get full file path the SDCard. Then concat strings to get the file path you want. Ex:
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "myFile.txt";
File f = new File(baseDir + File.separator + subfolder1 + File.separator + subfoler2, fileName);
In Java 7 we can do it this way:
Path path = Paths.get("/sdcard/mysdfile.txt");
BufferedWriter wrt = Files.newBufferedWriter(path, StandardCharsets.UTF_8, StandardOpenOption.APPEND);

Create pdf through java.io

I tried creating a pdf file out of another one(in my local drive) using java.io. The thing is a file with a .pdf extension got created but im unable to open the file, it says the file is already in use and most importantly the size of the file is too large and it keeps on increasing (origin file size : 5,777kB and the newly created one file size as of now is 38,567kB). Im not that much of skilled java programmer but still i would appreciate if anyone can give me an explanation ..
String path = "D:\\priya_Docs\\Android pdfs\\Professional_Android_Application_Development.pdf";
File file = new File(path);
System.out.println("Located a file " + file.isFile());
String filesArray = file.getPath();
File getFile = file.getAbsoluteFile();
FileInputStream fis = new FileInputStream(getFile);
FileOutputStream fos = new FileOutputStream(
"D:\\priya_Docs\\Androiddoc.pdf");
for (int b = fis.read(); b != -1;) {
fos.write(b);
}
Simple use,
FileUtils.copyFile()
you meet the two problems
first,you have to close the resource: fis and fos,or it will say the file already in use
second,you have to use the byte[] to receive the data because pdf file is organized in byte arrays
String path = "D:\\priya_Docs\\Android pdfs\\Professional_Android_Application_Development.pdf";
File file = new File(path);
System.out.println("Located a file " + file.isFile());
String filesArray = file.getPath();
File getFile = file.getAbsoluteFile();
FileInputStream fis = new FileInputStream(getFile);
FileOutputStream fos = new FileOutputStream(
"D:\\priya_Docs\\Androiddoc.pdf");
byte[] buff=new byte[1024];
int len;
while((len=fis.read(buff))>=0) {
fos.write(buff,0,len);
}
fis.close();
fos.close();

Creating a JAR file programmatically

I created a Jar file from my java code :
public void create() throws IOException{
FileOutputStream stream = new FileOutputStream(this.packagePath);
JarOutputStream out = new JarOutputStream(stream, new Manifest());
out.close();
//jarFile = new JarFile(new File(this.packagePath));
}
I get a META-INF directory, with a MANIFEST.MF file inside.
Now, when I want to add a file to the jar file :
public void addFile(File file) throws IOException{
//first, make sure the package already exists
if(!file.exists()){
throw new IOException("Make" +
" sure the package file already exists.you might need to call the Package.create() " +
"method first.");
}
FileOutputStream stream = new FileOutputStream(this.packagePath);
JarOutputStream out = new JarOutputStream(stream);
/*if(jarFile.getManifest()!=null){
out = new JarOutputStream(stream,jarFile.getManifest());
}else{
out=new JarOutputStream(stream);
}*/
byte buffer[] = new byte[BUFFER_SIZE];
JarEntry jarEntry = new JarEntry(file.getName());
jarEntry.setTime(file.lastModified());
out.putNextEntry(jarEntry);
//Write file to archive
FileInputStream in = new FileInputStream(file);
while (true) {
int nRead = in.read(buffer, 0, buffer.length);
if (nRead <= 0)
break;
out.write(buffer, 0, nRead);
}
in.close();
out.close();
}
when adding a file to the JAR archive using the above code, the META-INF directory with its MANIFEST.MF disappears and I get the newly added file.
I want to be able to add the file to the jar, and still get the manifest file. inside the manifest file, I want a line with the name of the newly added jar.
Thanks.
include the ant.jar in your project classpath
codeJar jar = new Jar();
//configure the jar object
jar.execute();
Look here for info about the parameters you can set.
I think you cannot add a new entry, because you cannot open jar package for "append". I think you must create a new jar file and copying entries from old, and add your entries.
FileOutputStream stream = new FileOutputStream(this.packagePath);
This line will create a new, empty file.
To edit a jar file, you will need to back up the old version and copy its entries into your new jar file.

Categories