Store File in Directory of Drive - java

{
headFile = File.createTempFile("HMh", ".tmp");
headCreated = true;
dataFile = File.createTempFile("HMd",".tmp");
dataCreated = true;
headOut = new DataOutputStream((new BufferedOutputStream(new FileOutputStream(headFile))));
dataOut = new DataOutputStream((new BufferedOutputStream(new FileOutputStream(dataFile))));
}
I have this code where headOut is being referenced and writing temp File to headFile, I want to replace the temporary File with the File to be stored in Directory in Windows D Drive so as too see the Files being stored physically . Please help with the code . As it creates multiple Temp File please let know to append the File name with the Date Time value so as it doesent overide existing Temp Files .

long l = new Date().getTime();
File.createTempFile("HMh"+l, ".tmp") It will append timestamps to your file.
Write file on drive.
File file = new File("C:\\filename.txt");
// creates the file
file.createNewFile();
// creates a FileWriter Object
FileWriter writer = new FileWriter(file);
// Writes the content to the file
writer.write("This\n is\n an\n example\n");

Related

I want to TAR a multiple files on JBOSS server in Eclipse using java

I have tried multiple examples... But non will work for me
Make tar file by Java
If I use above code, After reading the line TarOutputStream out = new TarOutputStream( new BufferedOutputStream( dest ) ); it just come out of the method(i.e.After reading that line... it won't executed the code which are after to that. The Sequence directly gone to the finally block where that method called).
For another example, I used apache common compress Jar. In that case it won't execute the java class itself it exit from the FormBean class.
The files are fetched from the database and it will be in a CSV format and all the files are placed in an Array List.
fileNames = "Security.smod."+SYSDATE;
strSavePath = D\:\\CMSREPORT\\reportZip\\
tarFunction(fileList, strSavePath, fileNames);
//Example function 1
private String tarFunction(ArrayList fileList, String strSavePath, String outFileName) {
int fileCountSize = fileList.size();
// Output file stream
FileOutputStream dest = new FileOutputStream( strSavePath );
// Create a TarOutputStream
TarOutputStream out = new TarOutputStream( new BufferedOutputStream( dest ) );
// Files to tar
File[] filesToTar=new File[3];
for(int i=0; i<fileCountSize; i++)
{
filesToTar[i]=new File((String) fileList.get(i);
}
for(File f:filesToTar){
out.putNextEntry(new TarEntry(f, f.getName()));
BufferedInputStream origin = new BufferedInputStream(new FileInputStream( f ));
int count;
byte data[] = new byte[2048];
while((count = origin.read(data)) != -1) {
out.write(data, 0, count);
}
out.flush();
origin.close();
}
}
For Example 2, I used apache.common.compress.1.2 as a jar.
In that case, It won't execute the java class, it exited from the FormBean class.
//Example function 2
private void tarFunc(){
try{
// Files to tar
File resource1 = new File((String) fileList.get(0));
File resource2 = new File((String) fileList.get(1));
File resource3 = new File((String) fileList.get(2));
// Output Stream - that will hold the physical TAR file
OutputStream tar_output = new FileOutputStream(new File(fileNames+".tar"));
// Create Archive Output Stream that attaches File Output Stream / and specifies TAR as type of compression
ArchiveOutputStream my_tar_ball = new ArchiveStreamFactory().createArchiveOutputStream(ArchiveStreamFactory.TAR, tar_output);
// Create Archieve entry - write header information
TarArchiveEntry tar_file = new TarArchiveEntry(resource1);
// length of the TAR file needs to be set using setSize method
tar_file.setSize(resource1.length());
my_tar_ball.putArchiveEntry(tar_file);
IOUtils.copy(new FileInputStream(resource1), my_tar_ball);
// Close Archieve entry, write trailer information
my_tar_ball.closeArchiveEntry();
// Repeat steps for the next file that needs to be added to the TAR
tar_file = new TarArchiveEntry(resource2);
tar_file.setSize(resource2.length());
my_tar_ball.putArchiveEntry(tar_file);
IOUtils.copy(new FileInputStream(resource2), my_tar_ball);
// Close Archieve entry, write trailer information
my_tar_ball.closeArchiveEntry();
tar_file = new TarArchiveEntry(resource3);
tar_file.setSize(resource3.length());
my_tar_ball.putArchiveEntry(tar_file);
IOUtils.copy(new FileInputStream(resource3), my_tar_ball);
// Close Archieve entry, write trailer information
my_tar_ball.closeArchiveEntry();
my_tar_ball.finish();
// Close output stream, our files are zipped
tar_output.close();
}catch(Exception e){
e.printStackTrace();
}
}
Anyone please help to solve this issue. Thank you:)

Copy files from one directory to another and append new files with timestamp instead of overwriting in Java

I want to copy files from source directory to destination. If the file already exists in the destination directory, then append the new file to be copied with its timestamp so that there is no overwrite. How do I check for duplicates and append timestamp to the new file name? Please help!
public static void copyFolder(File src, File dest)
throws IOException{
//list all the directory contents
String files[] = src.list();
for (String file : files) {
//construct the src and dest file structure
File srcFile = new File(src, file);
File destFile = new File(dest, file);
//recursive copy
copyFolder(srcFile,destFile);
}
}else{
//if file, then copy it
//Use bytes stream to support all file types
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
//copy the file content in bytes
while ((length = in.read(buffer)) > 0){
out.write(buffer, 0, length);
}
in.close();
out.close();
System.out.println("File copied from " + src + " to " + dest);
}
}
//construct the src and dest file structure
File srcFile = new File(src, file);
File destFile = new File(dest, file);
while (destFile.exists()) {
destFile = new File(dest, file + '-' + Instant.now());
}
In one case the destination file got named test-file.txt-2018-03-14T11:05:21.103706Z. The time given is in UTC. In any case you will end up with a name of file that doesn’t already exist (if the loop terminates, but I have a hard time seeing the scenario where it doesn’t).
You may want to append the timestamp only to plain files and reuse existing folders (directories), I don’t know your requirements here. And you may want to append the timestamp before the extension if there is one (to get test-file-2018-03-14T11:05:21.103706Z.txt instead). I trust you to make the necessary modifications.
You can check if the file exists using File.exist() method, if exists, you can open the file in the append mode
The code is something like this
File f = new File(oldName);
if(f.exists() && !f.isDirectory()) {
long currentTime=System.currentTimeMillis();
String newName=oldName+currentTime;
// do the copy
}

Before creating the file , deleting the file of previous day

I am creating a dat file in C: drive folder named abc as shown below , Now my file is generated everyday
now suppose if my file is generated today, then tommrow it will be also generated as usual
but when tommrow it is generated I have to make sure that earlier day file is deleted as the space in that folder is limited and this check is every time need to be done previos day file to be get deleted from that folder , please advise how to achieve this..
File file = new File(FilePath + getFileName()); //filepath is being passes through //ioc //and filename through a method
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fileOutput = new FileOutputStream(
file);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
fileOutput));
why not use file.delete() ?
File file = new File(FilePath + getFileName()); //filepath is being passes through //ioc //and filename through a method
if (file.exists()) {
file.delete(); //you might want to check if delete was successfull
}
file.createNewFile();
FileOutputStream fileOutput = new FileOutputStream(file);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fileOutput));
If your file name same in time to time no need to delete that. By running your code tomorrow, will over write file created today.
Consider following case
BufferedWriter bw=new BufferedWriter(new FileWriter("D:\\Test\test.txt"));
bw.write("abbbb");
bw.close(); // now this will create a test.txt in side Test folder
now run this by change writing String
BufferedWriter bw=new BufferedWriter(new FileWriter("D:\\test.txt"));
bw.write("hihi");
bw.close(); // now you can see file only containing hihi
You can change your code this way:
if (file.exists()) {
file.delete();
}
file.createNewFile();
And if it does not work, it's a matter of permission.
If you are using Java 7 then there is standard way to get file creation time, So that you can check if file is created in previous day and should be delete.
Path path = Paths.get("/filepath/");
BasicFileAttributes fileAttributes = Files.readAttributes(path, BasicFileAttributes.class);
System.out.println("creationTime:"+ fileAttributes.creationTime());

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);

File Path appearing in the Zipped File

I have a java program as below for zipping a folder as a whole.
public static void zipDir(String dir2zip, ZipOutputStream zos)
{
try
{
File zipDir= new File(dir2zip);
String[] dirList = zipDir.list();
byte[] readBuffer = new byte[2156];
int bytesIn = 0;
for(int i=0; i<dirList.length; i++)
{
File f = new File(zipDir, dirList[i]);
if(f.isDirectory())
{
String filePath = f.getPath();
zipDir(filePath, zos);
continue;
}
FileInputStream fis = new FileInputStream(f);
ZipEntry anEntry = new ZipEntry(f.getPath());
zos.putNextEntry(anEntry);
while((bytesIn = fis.read(readBuffer)) != -1)
{
zos.write(readBuffer, 0, bytesIn);
}
fis.close();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void main(){
String date=new java.text.SimpleDateFormat("MM-dd-yyyy").format(new java.util.Date());
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream("Output/" + date + "_RB" + ".zip"));
zipDir("Output/" + date + "_RB", zos);
zos.close();
}
My query here is. The target folder(+date+_RB) to be zipped is present inside the folder named Output. After successful zipping, when I extract the zipped file, I find a folder Output inside which the (+date+_RB) required folder is present. I need not want that Output folder after the extraction of the zipped file, rather it should directly extract the required folder alone. Please advise on the same.
UPDATE:
I tried Isaac's answer. While extracting the resultant zip file, no folders are getting extracted. Only the files inside all the folders are getting extracted. I just dont need the folder "Output" alone in the resultant zip file. But what the program does is, it doesnt extracts all other folders inside the Output folder, rather it just extracts the files inside those folders. Kindly advise on how to proceed...
It happens because of this:
ZipEntry anEntry = new ZipEntry(f.getPath());
f.getPath() will return Output/ at the beginning of the string. This is due to the flow of your program and how it (mis)uses File objects.
I suggest you construct a File object called, say, tmp:
File tmp = new File(dirList[i]);
The change the construction of f:
File f = new File(zipDir, tmp.getPath());
Then, change this:
ZipEntry anEntry = new ZipEntry(f.getPath());
To this:
ZipEntry anEntry = new ZipEntry(tmp.getPath());
I didn't have time to actually test it, but in a nutshell, your problem is due to how the File object is constructed.

Categories