When I create a file in java servlet, I can't find that file for opening. This is my code in servlet:
FileOutputStream fout;
try {
fout = new FileOutputStream("title.txt");
new PrintStream(fout).println(request.getParameter("txttitle"));
fout.close();
System.out.println(request.getParameter("txttitle"));
} catch (Exception e) {
System.out.println("I can't create file!");
}
Where I can find that file?
if you create file first as in
File f = new File("title.txt");
fout = new FileOutputStream(f);
then you use getAbsolutePath to return the location of where it has been created
System.out.println (f.getAbsolutePath());
Since you have'nt specified any directory for the file, it will be placed in the default directory of the process that runs your servlet container.
I would recommand you to always specify the full path of your your file when doing this kind of things.
If you're running tomcat, you can use System.getProperty("catalina.base") to get the path of the tomcat base directory. This can sometimes help.
Create a file object and make sure the file exists:-
File f = new File("title.txt");
if(f.exists() && !f.isDirectory()) {
fout = new FileOutputStream(f);
new PrintStream(fout).println(request.getParameter("txttitle"));
fout.close();
System.out.println(request.getParameter("txttitle"));
}
If the servlet cannot find the file give the full path to the file specified, like new File("D:\\Newfolder\\title.txt");
you should check first if the file doesn't exist ,create it
if(!new File("title.txt").exists())
{
File myfile = new File("title.txt");
myfile.createNewFile();
}
then you can use FileWriter or FileOutputStream to write to the file i prefer FileWriter
FileWriter writer = new FileWriter("title.txt");
writer.write("No God But Allah");
writer.close();
simply simple
Related
HI
I have a problem with writing to files, It works in the program(netbeans), but when it's exported to a jar file, it throws an exception, "FileNotFound." I checked inside the file folder inside the jar, and it was there, I think I need to use streams just as I use them in reading files:
InputStream u= FM.class.getResourceAsStream("/genex/files/data.txt");
try (InputStreamReader f = new InputStreamReader(u)) {what I wrote}
and that works perfectly fine, I just need a method like a getResourceAsStream() for OutputStreams
(btw, FM is the class name)
UPDATE: For those of you who really wanted to write files inside the jar, well, it's impossible. BUT, I found another way to store all of your files:
-writing
File file = new File("/GH/GX/save.txt");
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
try (PrintWriter writer = new PrintWriter(file)) {what you want to write}
-reading
File file = new File("/GH/GX/save.txt");
if (!file.exists()) {
return;
}
try (FileReader f = new FileReader(file)) {
//fr = new FileReader(f);
try (BufferedReader br = new BufferedReader(f)) {what you want to read}}
So I hope this article helped you :)
You can only read from files inside a jar not write to them.
I am trying to load some data saved in my property file in an Android Application.
I have put my property file under the src folder. Every time I try to load data from my file it keeps telling me FileNotFoundException open failed ENOENT (No such file or directory).
My Code is as follows:
This code is to save the file (new create)
File file = new File("src/com/example/testphonegap/SilverAngel.properties");
FileOutputStream fileOut = new FileOutputStream(file);
properties.store(fileOut, "Properties");
fileOut.close();
This code is to load data
properties = new Properties();
InputStream is = null;
// First try loading from the current directory
try {
File f = new File("src/com/example/testphonegap/SilverAngel.properties");
is = new FileInputStream(f);
// Try loading properties from the file (if found)
properties.load(is);
GetPersonaliseSettings();
GetUserSettings();
GetFavSettings();
}
catch ( Exception e ) {
is = null;
}
Can you tell me what I am doing wrong please? Is it where the file is saved or am I missing something in my code?
It's an Android Application, so the file is stored on the Android device and not on your computer.
If you want to save the file on the SD card you can write the following:
String root = Environment.getExternalStorageDirectory().toString();
File dir = new File(root + "/subfolderForYourApp");
dir.mkdirs();
This will create a subfolder for your application on the SD card.
To create a new file in this directory:
File file = new File(dir, "SilverAngel.properties");
FileOutputStream fileOut = new FileOutputStream(file);
properties.store(fileOut, "Properties");
fileOut.close();
Don't forget to add the permission to the manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
try this
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("com/example/testphonegap/SilverAngel.properties");
properties.load(inputStream);
make sure you don't add "src" before property file name.
Put it in the assets folder and load it from there.
AssetManager assetManager = context.getAssets();
InputStream inputStream = assetManager.open("SilverAngel.properties");
properties.load(inputStream);
I am trying to Compare last modified date of two excel files and replace the old file with new file.
In Scenario : When there is no file in the first place, so the code copies the file to that location and later reads it.
Issue is : It throws a FileNotFound exception when the excel file is not present on the server,even after writing the file to the
server(via code),but the file is not seen on the server. It works on
my machine(windows),but fails when deployed on server.
Again, it works like charm when the file is present on the server,while the old is being replaced by the new file.
Can you please help and explain on why its failing in the above scenario,and only on server ?
if(row.getValue("fileType").toString().equals("xlsx")&&checkindatefolder.after(localdate))
{
messagelist.add("we are going to get the replace file in the server");
InputStream inp=folder.getFile();
ZipInputStream izs = new ZipInputStream(inp);
ZipEntry e = null;
while ((e = izs.getNextEntry()) != null) {
System.out.println("e.isDirectory(): "+e.isDirectory());
if (!e.isDirectory()) {
filename=e.getName();
System.out.println("filename: "+filename);
FileOutputStream os=new FileOutputStream("path"+e.getName());
byte[] buffer = new byte[4096];
int read=0;
System.out.println("writing to file");
while ((read=izs.read(buffer))> 0) {
System.out.println("1111");
os.write(buffer,0,read);
}
System.out.println("writing to file complete");
inp.close();
os.flush();
os.close();
}
}
Do all parts of the path exist?
So in your example:
/u01/app/webapps/out/pj/Create.xlsx
Do all subdirectories exist?
/u01/app/webapps/out/pj
If not, than trying to write there might fail with a FileNotFoundException.
You should create the directories with Files.creatDirectories(Path) first.
I am trying to add an extension to the name of file selected by a JFileChooser although I can't get it to work.
This is the code :
final JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal = fc.showSaveDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File f = fc.getSelectedFile();
String name =f.getAbsoluteFile()+".txt";
f.renameTo(new File(name));
FileWriter fstream;
try {
fstream = new FileWriter(f);
BufferedWriter out = new BufferedWriter(fstream);
out.write("test one");
out.close();
} catch (IOException ex) {
Logger.getLogger(AppCore.class.getName()).log(Level.SEVERE, null, ex);
}
}
I can't figure out why this doesn't work. I also tried using getPath() and getCanonicalPath() but the result is the same. The file is created at the directory selected, although without a ".txt" extension.
It seems to me that all you want to do is to change the name of the file chosen, as opposed to renaming a file on the filesystem. In that case, you don't use File.renameTo. You just change the File. Something like the following should work:
File f = fc.getSelectedFile();
String name = f.getAbsoluteFile()+".txt";
f = new File(name);
File.renameTo attempts to rename a file on the filesystem. For example:
File oldFile = new File("test1.txt");
File newFile = new File("test2.txt");
boolean success = oldFile.renameTo(newFile); // renames test1.txt to test2.txt
After these three lines, success will be true if the file test1.txt could be renamed to test2.txt, and false if the rename was unsuccessful (e.g. test1.txt doesn't exist, is open in another process, permission was denied, etc.)
I will hazard a guess that the renaming you are attempting is failing because you are attempting to rename a directory (you are using a JFileChooser with the DIRECTORIES_ONLY option). If you have programs using files within this directory, or a Command Prompt open inside it, they will object to this directory being renamed.
You could also use the Files.move utility from Google Guava libraries to rename a file. Its easier than writing your own method.
From the docs:
Moves the file from one path to another. This method can rename a file or move it to a different directory, like the Unix mv command.
You are writing to the wrong file. When you call renameTo, the current file doesn't change it's path. Try this:
final JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal = fc.showSaveDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File f = fc.getSelectedFile();
String name =f.getAbsoluteFile()+".txt";
File f2 = new File(name);
f.renameTo(f2);
FileWriter fstream;
try {
fstream = new FileWriter(f2);
BufferedWriter out = new BufferedWriter(fstream);
out.write("test one");
out.close();
} catch (IOException ex) {
Logger.getLogger(AppCore.class.getName()).log(Level.SEVERE, null, ex);
}
}
If you want to Rename the file then there is must to close all the object (like FileReader,FileWriter ,FIS ,FOSmeans close the the reading file object and then rename it
You need to create a new instance to refer to the new name of the file
oldFile = new File(newName);
i need some help with creating file
Im trying in the last hours to work with RandomAccessFile and try to achieve the next logic:
getting a file object
creating a temporary file with similar name (how do i make sure the temp file will be created in same place as the given original one?)
write to this file
replace the original file on the disk with the temporary one (should be in original filename).
I look for a simple code who does that preferring with RandomAccessFile
I just don't how to solve these few steps right..
edited:
Okay so ive attachted this part of code
my problem is that i can't understand what should be the right steps..
the file isn't being created and i don't know how to do that "switch"
File tempFile = null;
String[] fileArray = null;
RandomAccessFile rafTemp = null;
try {
fileArray = FileTools.splitFileNameAndExtension(this.file);
tempFile = File.createTempFile(fileArray[0], "." + fileArray[1],
this.file); // also tried in the 3rd parameter this.file.getParentFile() still not working.
rafTemp = new RandomAccessFile(tempFile, "rw");
rafTemp.writeBytes("temp file content");
tempFile.renameTo(this.file);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
rafTemp.close();
}
try {
// Create temp file.
File temp = File.createTempFile("TempFileName", ".tmp", new File("/"));
// Delete temp file when program exits.
temp.deleteOnExit();
// Write to temp file
BufferedWriter out = new BufferedWriter(new FileWriter(temp));
out.write("Some temp file content");
out.close();
// Original file
File orig = new File("/orig.txt");
// Copy the contents from temp to original file
FileChannel src = new FileInputStream(temp).getChannel();
FileChannel dest = new FileOutputStream(orig).getChannel();
dest.transferFrom(src, 0, src.size());
} catch (IOException e) { // Handle exceptions here}
you can direct overwrite file. or do following
create file in same directory with diff name
delete old file
rename new file