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
Related
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
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.
The following code writes a string to a specific file.
String content = "Text To be written on a File";
File file = new File("c:/file.txt");
FileOutputStream foutput = new FileOutputStream(file);
if (!file.exists()) {
file.createNewFile();
}
byte[] c = content.getBytes();
foutput.write(c);
foutput.flush();
foutput.close();
I want to use this code in a Jbutton so every time the user clicks it, it writes the string to a NEW text file NOT OVERWRITE the existed one. I tried to do but I couldn't get the result.
Thank you in advance.
There's a couple of different ways you can get this result, it really depends on the application. The two easiest ways to do this would to be either:
Append the current timestamp to the file name
Use the File API to create a "temp file" in the directory, which is guarenteed to have a unique name
Option 1:
String baseDir = "c:/";
File newFile = new File(baseDir, "file_" + System.currentTimeMillis() + ".txt");
// do file IO logic here...
Option 2:
String baseDir = "c:/";
File newFile = File.createTempFile("file", ".txt", new File(baseDir));
// do file IO logic here...
If you want to write it to a new file, you have to create a new file. The name of the text file is always file.txt in your case.
Try this:
private int filecounter = 0; // this is the member of your class. Outside the function.
//inside your function
File file = new File("c:/file" + Integer.(filecounter).toString() + ".txt");
// you do something here.
filecounter++;
This way, your files will be stored as file0.txt, file1.txt etc.
I have a .jar that has two .dll files that it is dependent on. I would like to know if there is any way for me to copy these files from within the .jar to a users temp folder at runtime. here is the current code that I have (edited to just one .dll load to reduce question size):
public String tempDir = System.getProperty("java.io.tmpdir");
public String workingDir = dllInstall.class.getProtectionDomain().getCodeSource().getLocation().getPath();
public boolean installDLL() throws UnsupportedEncodingException {
try {
String decodedPath = URLDecoder.decode(workingDir, "UTF-8");
InputStream fileInStream = null;
OutputStream fileOutStream = null;
File fileIn = new File(decodedPath + "\\loadAtRuntime.dll");
File fileOut = new File(tempDir + "loadAtRuntime.dll");
fileInStream = new FileInputStream(fileIn);
fileOutStream = new FileOutputStream(fileOut);
byte[] bufferJNI = new byte[8192000013370000];
int lengthFileIn;
while ((lengthFileIn = fileInStream.read(bufferJNI)) > 0) {
fileOutStream.write(bufferJNI, 0, lengthFileIn);
}
//close all steams
} catch (IOException e) {
e.printStackTrace();
return false;
} catch (UnsupportedEncodingException e) {
System.out.println(e);
return false;
}
My main problem is getting the .dll files out of the jar at runtime. Any way to retrieve the path from within the .jar would be helpful.
Thanks in advance.
Since your dlls are bundeled inside your jar file you could just try to acasses them as resources using ClassLoader#getResourceAsStream and write them as binary files any where you want on the hard drive.
Here is some sample code:
InputStream ddlStream = <SomeClassInsideTheSameJar>.class
.getClassLoader().getResourceAsStream("some/pack/age/somelib.dll");
try (FileOutputStream fos = new FileOutputStream("somelib.dll");){
byte[] buf = new byte[2048];
int r;
while(-1 != (r = ddlStream.read(buf))) {
fos.write(buf, 0, r);
}
}
The code above will extract the dll located in the package some.pack.age to the current working directory.
Use a class loader that is able to locate resources in this JAR file. Either you can use the class loader of a class as Peter Lawrey suggested, or you can also create a URLClassLoader with the URL to that JAR.
Once you have that class loader you can retrieve a byte input stream with ClassLoader.getResourceAsStream. On the other hand you just create a FileOutputStream for the file you want to create.
The last step then is to copy all bytes from the input stream to the output stream, as you already did in your code example.
Use myClass.getClassLoader().getResourceAsStream("loadAtRuntime.dll"); and you will be able to find and copy DLLs in the JAR. You should pick a class which will also be in the same JAR.
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);