I am attempting to create something like an iso of the hard drive of a computer in java, but with no data in the files. Like a file tree, but an iso. This happens on client A.
The point of this is to transfer this ISO file tree over GAE to another client (Let's say client B) who should be able to mount the iso on his computer using windows explorer.
The above is what I want to achieve - I know it is very specific, sorry about this. However, all I want to know is how to create an ISO (or some other mountable image of a hard drive) that contains no data in the files.
No data in the files = the files are still there (I must be able to see the names of the files), but they are empty. You know. Open them with notepad and all you get is "" in the file. Or a space. Whatever. The point is to make the iso small in size so I can transfer into to client B, instead of transfering the whole hard drive. After this client B can choose the file he wants to fetch of the other computer, but that's a different story.
The question:
How to create something like an ISO of the hard drive of a computer in Java, but with no data in the files?
Feel free to recommend a solution that has the same functionality but takes a different approach.
Update:
Stuffed the ISO approach. Created an object with lots of trees of files. Contact me somehow if u want to do the same.
Just to copy the entire file structure with empty files:
// you may want to actually handle the IOException rather than just throwing it
public static void main(String[] args) throws IOException
{
makeFileStructure(new File("someDirectory"), "someDestinationDirectory");
}
static void makeFileStructure(File src, String dest) throws IOException
{
for (File f: src.listFiles())
{
String newPath = dest + File.separatorChar + f.getName();
if (f.isDirectory())
{
if (!new File(newPath).mkdirs())
// you may want to handle this better
throw new IOException("Directory could not be created!");
makeFileStructure(f, newPath);
}
else
new File(newPath).createNewFile();
}
}
Just make sure "someDestinationDirectory" isn't a subdirectory of "someDirectory", otherwise things will obviously not go very well.
Pretty sure you'll need an external library for creating an ISO image (if you want to create it). Try Googling it. But it might be easier to just do it with an external application and a batch file (after having run the above code).
Related
I know how to read file one by one from a folder in java.But I want to know If I give a folder named Search and in Search folder it has 3 different folders named A,B,C and each folder has multiple text files.I want to read all files which has in A,B,C folder by giving folder name Search as user input.can it be possible? I am new in java.
Sure it is. This sounds like you want to walk a folder (meaning, you want to do something for every file in a given folder, and for every subfolder in that folder, and for every file in that subfolder, and for every subfolder in the subfolder, ad infinitum, until you've seen everything).
You can handroll a recursive algorithm yourself using Files.newDirectoryStream, or, just use the existing API:
Path folderToWalk = Paths.get("/path/to/folder");
Files.walkFileTree(folderToWalk, new SimpleFileVisitor<Path>() {
#Override public visitFile(Path f, BasicFileAttributes attrs) throws IOException {
// this is invoked for _every_ file anywhere in the folder structure.
}
});
You can also add methods that are called if a file cannot be visited (for example, because of access rights issues), as well as if you want to get directory names - see the API.
Within visitFile, you can do whatever you want. For example, if you want to fully read the file into a string, you can invoke Files.readString(f);. See the Files API for all the stuff you can do*.
*) You said 'I know how to read...' - it's possible you've learned the obsolete, outdated java.io.FileInputStream API. Don't use that - use the Files API. It is less boneheaded about errors and charset encoding, gives you more stuff (such as giving you access to the file owner's name and group, and softlinks), and more high-level API primitives, such as 'just read the whole thing into a string for me please', and, 'just walk this entire file tree for me please'.
This question already has answers here:
How to recover deleted files using Java? [closed]
(2 answers)
Closed 4 years ago.
This is my code to delete '.txt' files from specific folder(/home/user). But once it is deleted I don't know how to recover these deleted files.
Please show me some example code (if possible), to achieve this.
Is it possible in java? If so then please help me (I am happy to use any other language.)
import java.*;
import java.io.File;
class CountFiles
{
public static void main(String args[])
{
String dirPath="/home/user";
File f = new File(dirPath);
File[] files = f.listFiles();
int s=files.length;
System.out.println("Number of files in folder "+s);
for(int i=0;i <s; i++)
{
if (files[i].isFile())
{
String FilesName = files[i].getName();
System.out.println(FilesName);
if (FilesName.endsWith(".txt") || FilesName.endsWith(".TXT"))
{
boolean success = files[i].delete();
vif (!success) throw new IllegalArgumentException("Delete: deletion failed");
else System.out.println("file deleted");
}
System.out.println("file deleted out side.....");
}
}
}
}
Yes, it is possible in Java, however for low level or OS specific tasks it may be better to use a native language.
The below info applies to both Java and other languages:
If you have control of the files before they are deleted then you can simply make a copy/backup of the file before you delete it.
If you want to recover data from a system trash/recycle bin then you need a specific solution for each OS.
However, if you do are not able to backup the files first, and do not have access to a trash folder, then you can NEVER EVER be 100% sure that you can recover the data (See edit below for more details). You can however read raw data from the storage device. This is an incredibly complex and advanced subject. If you have to ask the question then you should not be trying to write code to do it without first doing a lot of your own research.
Before reading on, refer to this answer showing how you can read raw bytes from a storage device: How to recover deleted files using Java?
After reading the accepted answer you also need to consider:
You can access the drive sector by sector, but you will have to
interpret the data differently for different file systems (FAT, NTFS,
HPFS, and more)
You cannot use a file path to get a deleted file, you need to scan the whole drive and make an educated guess at what to recover,
or ask for user input so they can choose what to recover.
The task can be a long and complex one, and you have to interpret the raw data to see if it is a valid plain text file, as well as finding it's start and end.
Edit to include the comment from Bill:
Once a file has been deleted, any further action that the computer takes (Including using recovery tools) has the potential to write over the data that you want to recover. The best solution is to force shutdown the PC, and clone the drive so that data recovery can be done on another PC using the clone while keeping the original safe.
I am building a database using db4o that contains files and information about the files, but want to do so in a way that does not require a file system behind it (I specifically want a file system to not exist because of the complexity of the file relations: there would be no way to design such a file system in an intelligent way for the web of items we work with.)
So I know that the File class is a pointer to a file in a file system, but I want the actual file to be encompassed in the object I'm working with. I would use a string, but the objects can often be load binaries, images, or movies, so that would be a misuse of the type that I do not want.
I have been searching quite a bit, but haven't found a solution and most of my searches just lead me to explanations of the File class.
Example object I want:
public class FileContainer {
private Date addedDate;
private String checkSum;
private Boolean criticalState;
private FileContainer previousVersion;
private String addedBy;
private FileObject file;
}
where the FileObject is simply the actual file.
Thank you for the assistance.
As of Java 7 you can have artificial file systems, like the ZipFileSystem, which is very near to what you want. In fact adding a file, removing a file, renaming a file, maintaining relative paths between two file systems. All such examples would be usable for your file system too.
Also the new nio API can provide file attributes by free key.
The advantage is using one generic API for all file systems. The class Path also holds its file system for instance.
Files are categorized by file-extension. So my question is, how to identify the file type even the file extension has been changed.
For example, i have a video file with name myVideo.mp4, i have changed it to myVideo.txt. So if i double-click it, the preferred text editor will open the file, and won't open the exact content. But, if i play myVideo.txt in a video player, the video will be played without any problem.
I was just thinking of developing an application to determine the type of file without checking the file-extension and suggesting the software for opening the file. I would like to develop the application in Java.
One of the best libraries to do this is Apache Tika. It doesn't only read the file's header, it's also capable of performing content analysis to detect the file type. Using Tika is very simple, here's an example of detecting a file's type:
import java.net.URL;
import org.apache.tika.Tika; //Including Tika
public class TestTika {
public static void main(String[] args) {
Tika tika = new Tika();
String fileType = tika.detect(new URL("http://example.com/someFile.jpg"));
System.out.println(fileType);
}
}
Structure, magic numbers, metadata, strings and regular expressions, heuristics and statistical analysis... the tool will only be as good as the database of rules behind it.
Try DROID (Digital Record Object IDentification tool) for identifying file types; Java, Net BSD-licensed. It is a free project of the National Archives UK, unrelated to Android. Source is available on Github and Sourceforge. The DROID documentation is good, there's also a getting started guide from the Digital Preservation Coalition.
See also Darwinsys file and libmagic.
There's a tool called TrID that does what you are after - it current supports 5033 different file types - and can be trained to add new types. On *nix systems, there's also the file command, which does something similar.
well, its like having a database of file-format you want to read without looking for extension in your app. Exactly as Linux does. So whenever you open a file, you need to check file-format database which type it belongs to. Though Not sure how will it work for different file types, but most of files have fixed header format, be it zip, pdf, mpg, avi, png, etc.. so this approach should work
You could try MimeUtil2, but it's quite old and though not up2date. The best way is still the file extension.
But the solution from Adam is not as bad as you think. You could build your platform independent solution using a wrapper around command line calls. I think you will get much better results using this method.
The following code snippet retrieves information about the file type
final File file = new File("file.txt");
System.out.println("File type is: " + new MimetypesFileTypeMap().getContentType(file));
Hopefully, it may help you
For those unfamiliar with JNotify, this is a library which provides an easy way to monitor events in a directory.
For instance, when a file gets deleted in the selected folder, the method "fileDeleted" gets called, along with a few parameters. Here's an example of the fileDeleted method:
public void fileDeleted(int wd, String rootPath, String name) {
print("deleted " + rootPath + " : " + name);
}
Now, I would like to know if the deleted file was a file or directory. My usual approach is to create a new File object with the given path, and use the methods isFile() and isDirectory()
However, since this file is already deleted, these methods always return false.
So here's my concrete question: I have the path to a deleted file or directory, how can I tell wether it was a file or a directory? Is there a workaround to this? What's the best practice to do here?
Thank you in advance.
I suggest using a better API for this, like Commons IO. It has this distinction in its interface org.apache.commons.io.monitor.FileAlterationListener and its methods onFile...(), onDirectory...(). Alternatively, and this is probably the best approach, use the new standard feature for this that comes with Java 7, WatchService, as discussed here.
How big is the directory structure you're looking at?
My first instinct is to build an internal representation of the directory structure, using some simple graph traversal algorithm, and then do a lookup every time something is removed to figure out what it was.
<edit>
If you know your directory structure is a strict tree you can use a simple recursion to traverse the file system, and create a map of Files or Strings to boolean, so you can do an easy lookup. Then, once you've got the map built it should be easy to maintain using the JNotify events.
<edit/>
even for medium-sized directories I would think this could be made pretty quick. What is this for? Might there be another way of going about achieving the same goal?
I am facing the same problem. Yet as far as I understand it, Java's WatchService does not allow monitoring of subdirectories, so I cannot use it (task is to monitor changes to a structure containing ~40K folders). I will try and go ahead using the simple (and fallible) heuristic
If it contains a dot ('.'), it's a file.
I will post updates if I come across something more sophisticated...