Java File Tools

Platform:  Java
Published  Jul 10, 2012
Updated  Aug 06, 2012
Hawkee seems to be a little lack luster lately, and with my lack of development lately I figured I'd toss in a small snippet I made to make handling files easier. Java can be somewhat difficult to manage files with, and with each project that required logging, or database-like file structures I had to create another method to handle it. So I decided to create this snippet which can be attached to any project needing file manipulating tools. It can execute, copy, write, read, move, manipulate files, and it's data.

A few things to note:
- Not all files can be executed, only ones that are deemed "executable" by the runtime environment.
- getFileContents() - Preserves the files contents as they appear in the file, all inside of a String object; lines and all.
- copyTo(String) - Updated with a different method that will successfully copy any file. The file writing portion of the "copyTo" method is borrowed for the time being as it was more effective at copying data from one file location top the other than my original mechanics. import java.io.*;

public class FileUtil {

private File file;

public FileUtil() { }

public FileUtil(File f) {
file = f;
File dir = new File(file.getParent() + "/");
if (!file.exists()) {
try { dir.mkdirs(); file.createNewFile(); } catch (Exception e) { }
}
}

public FileUtil(String path) {
file = new File(path);
File dir = new File(file.getParent() + "/");
if (!file.exists()) {
try { dir.mkdirs(); file.createNewFile(); } catch (Exception e) { }
}
}

public void writeToFile(String data, boolean append) {
try {
FileOutputStream fos = new FileOutputStream(file,append);
fos.write(data.getBytes());
fos.close();
} catch (Exception e) { }
}

public String getFileContents() {
String in = "", out = "";
try {
BufferedReader br = new BufferedReader(new FileReader(file));

while ((in = br.readLine()) != null) { out += in + "\r\n"; }

br.close();
} catch (Exception e) { }
return out;
}

protected void execute() {
if (file.canExecute()) {
try {
Runtime run = Runtime.getRuntime();
Process p = run.exec(file.getPath());
} catch (Exception e) { }
}
}

public void copyTo(String path) {
try {
File dest = new File(path + "/");
dest.mkdirs();
dest = new File(path + file.getName());
dest.createNewFile(); //Destination File path

InputStream is = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(dest);
byte[] buf = new byte[64 * 1024];
int len = 0;

while((len = is.read(buf)) != -1) { fos.write(buf, 0, len); }

fos.flush();
fos.close();
is.close();
} catch (Exception e) { }
}

public File getFileObject() { return file; }
}

Comments

Sign in to comment.
Are you sure you want to unfollow this person?
Are you sure you want to delete this?
Click "Unsubscribe" to stop receiving notices pertaining to this post.
Click "Subscribe" to resume notices pertaining to this post.