Monday, May 6, 2013

Disk Helper


Utility class for saving, opening and zipping files.

public class DiskHelper
{

/**
* saveToDisk i openFile
*/
public static void printFileObject(FileObject fo)
{
File file = saveToDisk(fo, fo.getFilename());
openFile(file);
}

public static File saveToDisk(FileObject fo, String fileName)
{
String pdfSuffix = "";
if (!fileName.contains(".pdf"))
{
pdfSuffix = ".pdf";
}

File file = new File("c://tmp//" + fileName + pdfSuffix);

int i = 0;
while (file.exists())
{
i++;
file = new File("c://tmp//" + fileName.replace(".pdf", "") + "_" + i + ".pdf");
}

System.out.println("file.exists: " + file.exists());

OutputStream os;
try
{
os = new FileOutputStream(file);
os.write(fo.getContent());
os.flush();
os.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return file;

}

public static void openFile(File file)
{
StringBuilder sb = new StringBuilder();
sb.append("cmd.exe /C start ");
sb.append(file.getAbsolutePath());
System.out.println("openFile: " + sb);
try
{
Runtime.getRuntime().exec(sb.toString());
}
catch (IOException e)
{
e.printStackTrace();
}
}

private static int byteValue = 1024;

/**
* http://www.mkyong.com/java/how-to-compress-files-in-zip-format/
*/
public static void zipFile(String fileName, File... files)
{
byte[] buffer = new byte[1024];

try
{
File zipfile = new File("C:\\tmp\\" + fileName + ".zip");
FileOutputStream fos = new FileOutputStream(zipfile);
ZipOutputStream zos = new ZipOutputStream(fos);

for (File file : files)
{
System.out.println("file.getName(): " + file.getName() + ", file.length(): " + file.length() / byteValue + " KB");
ZipEntry ze = new ZipEntry(file.getName());
zos.putNextEntry(ze);
FileInputStream in = new FileInputStream(file.getAbsoluteFile());
System.out.println("file.getAbsoluteFile(): " + file.getAbsoluteFile());

int len;
while ((len = in.read(buffer)) > 0)
{
zos.write(buffer, 0, len);
}

in.close();
}

System.out.println("zipfile.getName(): " + zipfile.getName() + ", zipfile.length(): " + zipfile.length() / byteValue + " KB");

zos.closeEntry();
zos.close();

System.out.println("Done");

}
catch (IOException ex)
{
ex.printStackTrace();
}
}

public static void deleteFiles(File... files)
{
for (File file : files)
{
file.delete();
}
}

}



public class FileObject
{
private String filename;
private byte[] content;

public byte[] getContent()
{
return content;
}

public void setContent(byte[] content)
{
this.content = content;
}

public String getFilename()
{
return filename;
}

public void setFilename(String filename)
{
this.filename = filename;
}

}

No comments:

Post a Comment