FileHelper.java
| Index Score | ||
|---|---|---|
![]() |
![]() |
org.xnap.util |
![]() |
![]() |
XNap 3 |
View: Reasons, Metrics, Source Code
These are the metrics that contribute to the Enerjy Score for this file, ranked by impact. So the metrics listed at the top influence the score to a greater extent that the metrics listed at the bottom.
/*
* XNap - A P2P framework and client.
*
* See the file AUTHORS for copyright information.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.xnap.util;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.NotSerializableException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.URL;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import java.util.StringTokenizer;
import org.apache.log4j.Logger;
import org.xnap.loader.XNapClassLoader;
import org.xnap.search.MediaType;
import org.xnap.search.SearchManager;
/**
* Provides a set of static methods that help with file manipulation.
*/
public class FileHelper
{
//--- Constant(s) ---
//--- Data field(s) ---
private static Logger logger = Logger.getLogger(FileHelper.class);
//--- Constructor(s) ---
//--- Method(s) ---
/**
* Creates and returns a file in the incomplete directory.
*/
public static File createIncompleteFile(String filename)
throws IOException
{
File path = new File(Preferences.getInstance().getIncompleteDir());
return FileHelper.createUnique(path, filename);
}
/**
* Creates a unique file by inserting digits into <code>filename</code>.
*
* @return the created file
*/
public static synchronized File createUnique(String filename)
throws IOException
{
logger.debug("FileHelper: creating unique: " + filename);
File f = new File(uniqueName(filename));
f.createNewFile();
return f;
}
/**
* Creates a unique file in by inserting digits into <code>filename</code>.
*
* @param path the path of the file to create
* @param filename the name of the file to create
* @return the created file
*/
public static synchronized File createUnique(File path, String filename)
throws IOException
{
if (path.isDirectory() || path.mkdirs()) {
// sanitize filename
filename = toFilename(filename);
return createUnique
(path.getAbsolutePath() + File.separator + filename);
}
throw new FileNotFoundException();
}
/**
* Moves <code>file</code> to <code>path</code> but renames
* <code>filename</code> if it already exists in the target path.
*
* @param file the file to move
* @param path the target path
* @param filename the new filename for <code>file</code>
* @return the moved file
*/
public static synchronized File moveUnique
(File file, String path, String filename) throws IOException
{
String newFilename = appendSeparator(path) + toFilename(filename);
logger.debug("moveUnique new name: " + newFilename);
if (newFilename.equals(file.getAbsolutePath())) {
return file;
}
File p = new File(path);
if (p.isDirectory() || p.mkdirs()) {
File newFile = new File(uniqueName(newFilename));
logger.debug("moveUnique new file: " + newFile);
if (move(file, newFile)) {
return newFile;
}
else {
throw new FileNotFoundException
("Could not rename " + file.getAbsolutePath() + " to "
+ newFile.getAbsolutePath());
}
}
else {
throw new FileNotFoundException
("Could not create " + p.getAbsolutePath());
}
}
/**
* Moves <code>file</code> to <code>path</code>.
*
* @see #moveUnique(File, String, String)
*/
public static synchronized File moveUnique(File file, String path)
throws IOException
{
return moveUnique(file, path, file.getName());
}
/**
* Moves a file. Tries a rename, if fails, copies file.
*/
public static boolean move(File source, File dest) throws IOException
{
if (!source.renameTo(dest)) {
copy(source, dest);
source.delete();
}
return true;
}
/**
* Copies <code>source</code> to <code>dest</code>. If dest already exists
* it is overwritten.
*
* @param source the source file
* @param dest the destination file
*/
public static void copy(File source, File dest) throws IOException
{
InputStream in = new FileInputStream(source);
try {
copy(in, new FileOutputStream(dest));
}
finally {
try {
in.close();
}
catch (IOException e) {
}
}
}
/**
* Copies <code>source</code> to <code>dest</code>. If dest already exists
* it is overwritten.
*
* @param source the source file
* @param dest the destination file
*/
public static void copy(InputStream inStream, OutputStream outStream)
throws IOException
{
BufferedInputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(inStream);
out = new BufferedOutputStream(outStream);
byte buffer[] = new byte[512 * 1024];
int count;
while ((count = in.read(buffer, 0, buffer.length)) != -1) {
out.write(buffer, 0, count);
}
out.flush();
}
finally {
if (in != null) {
try {
in.close();
}
catch (IOException e) {
}
}
if (out != null) {
try {
out.close();
}
catch (IOException e) {
}
}
}
}
/**
* Returns the lower case extension part of <code>filename</code>.
*
* @see #name(String)
*/
public static String extension(String filename)
{
return StringHelper.lastToken(filename, ".").toLowerCase();
}
/**
* Returns the name part of <code>filename</code>.
*
* @see #extension(String)
*/
public static String name(String filename)
{
int i = filename.lastIndexOf(".");
return (i < 1) ? filename : filename.substring(0, i);
}
/**
* Returns the path of the download dir where <code>filename</code>
* should be downloaded to.
*/
public static String getDownloadDir(String filename)
{
Preferences p = Preferences.getInstance();
MediaType type = SearchManager.getMediaType(filename);
if (type != null) {
String dir = p.getMediaTypeDownloadDir(type.getRealm());
if (dir.length() > 0) {
return dir;
}
}
return p.getDownloadDir();
}
public static URL getResource(String filename)
{
return XNapClassLoader.getInstance().getResource(filename);
}
public static InputStream getResourceAsStream(String filename)
{
return XNapClassLoader.getInstance().getResourceAsStream(filename);
}
/**
* Creates unique filename.
*/
public static String uniqueName(String filename)
{
return uniqueName(filename, "");
}
public static String uniqueName(String filename, String infix)
{
String extension = extension(filename);
if (extension.length() > 0) {
extension = "." + extension;
filename = name(filename);
}
if (infix.length() > 0) {
infix = "." + infix;
}
if (exists(filename + infix + extension)) {
for (int i = 1; ; i++) {
if (!exists(filename + infix + "." + i + extension))
return (filename + infix + "." + i + extension);
}
}
return filename + infix + extension;
}
/**
* Returns true, if filename exists; false, otherwise.
*/
public static boolean exists(String filename)
{
return (new File(filename)).exists();
}
/**
* Checks for existence of .xnap folder in the user's home directory and
* returns the absolute path with a file separator appended.
*
* @param subdir a sub directory that is located in ~/.xnap/ or created if
* it does not exist
* @return empty string, if subdir could not be created; absolute path,
* otherwise
*/
public static final String getHomeDir(String subdir)
{
StringBuffer sb = new StringBuffer();
sb.append(XNapClassLoader.getHomeDir());
if (subdir.length() > 0) {
sb.append(subdir);
sb.append(File.separatorChar);
}
String dir = sb.toString();
File file = new File(dir);
if (file.isDirectory() || file.mkdirs()) {
return dir;
}
return "";
}
/**
* Returns the absolute path of the ~/.xnap/ directory.
*
* @see #getHomeDir(String)
*/
public static final String getHomeDir()
{
return getHomeDir("");
}
/**
* Appens a file separator to <code>path</code> if it does not have a
* trailing one.
*/
public static String appendSeparator(String path)
{
if (path.length() > 0 && !path.endsWith(File.separator)) {
return path + File.separator;
}
else {
return path;
}
}
public static String directory(String dir)
{
dir = dir.trim();
if (dir.length() == 0) {
dir = System.getProperty("user.dir");
}
return appendSeparator(dir);
}
public static String directories(String dirs)
{
StringTokenizer st = new StringTokenizer(dirs, ";");
StringBuffer sb = new StringBuffer();
while (st.hasMoreTokens()) {
String s = st.nextToken().trim();
if (s.length() > 0) {
File f = new File(s);
sb.append(f.getAbsolutePath());
sb.append(";");
}
}
dirs = sb.toString();
// remove trailing semicolon
return (dirs.length() > 0) ? dirs.substring(0, dirs.length() - 1) : "";
}
/**
* Shortens <code>file</code> by <code>bytes</code> bytes.
*/
public static void shorten(File file, long bytes)
{
try {
RandomAccessFile f = new RandomAccessFile(file, "rw");
try {
f.setLength(Math.max(f.length() - bytes, 0));
}
catch (IOException e) {
}
finally {
try {
f.close();
}
catch (IOException e) {
}
}
}
catch (IOException e) {
}
}
/**
* Stores <code>props</code> in <code>file</code>.
*/
public static void writeProperties(File file, Properties props)
throws IOException
{
FileOutputStream out = null;
try {
out = new FileOutputStream(file);
props.store(out, "This file was automatically generated.");
}
catch (IOException e) {
throw(e);
}
finally {
try {
if (out != null) {
out.close();
}
}
catch (Exception e) {
}
}
}
/**
* Reads all objects from <code>file</code> using serialization and adds
* them to <code>c</code>.
*/
public static void readBinary(File file, Collection c) throws IOException
{
logger.debug("reading binary file: " + file);
ObjectInputStream in = null;
try {
in = new ObjectInputStream(new FileInputStream(file));
int size = in.readInt();
for (int i = 0; i < size; i++) {
try {
Object o = in.readObject();
if (o != null) {
c.add(o);
}
}
catch (IOException e) {
throw e;
}
catch (Exception e) {
logger.warn("error while reading binary file", e);
}
}
}
finally {
try {
if (in != null) {
in.close();
}
}
catch (IOException e) {
}
}
}
public static String readText(File file) throws IOException
{
return readText(new FileInputStream(file));
}
/**
* Reads a text file.
*/
public static String readText(InputStream inStream) throws IOException
{
BufferedReader in
= new BufferedReader(new InputStreamReader(inStream));
try {
StringBuffer sb = new StringBuffer();
String s;
while ((s = in.readLine()) != null) {
sb.append(s);
sb.append("\n");
}
return sb.toString();
}
finally {
try {
in.close();
}
catch (IOException e) {
// this exception gets lost
}
}
}
public static String[] readConfig(File file) throws IOException
{
return readConfig(new FileInputStream(file));
}
/**
* Reads a text file. Ignores all lines empty lines and lines that
* start with a '#' character.
*
* @return always a valid array, possibly with size 0
*/
public static String[] readConfig(InputStream inStream) throws IOException
{
BufferedReader in
= new BufferedReader(new InputStreamReader(inStream));
try {
List lines = new LinkedList();
String s;
while ((s = in.readLine()) != null) {
s = s.trim();
if (s.length() == 0 || s.startsWith("#")) {
continue;
}
lines.add(s);
}
return (String[])lines.toArray(new String[0]);
}
finally {
try {
in.close();
}
catch (IOException e) {
// this exception gets lost
}
}
}
/**
* Replaces all special characters in filename by '_'.
*/
public static String toAscii(String filename)
{
String s = filename;
s = s.replace('\t', '_');
s = s.replace(' ', '_');
s = s.replace(File.separatorChar, '_');
s = s.replace(File.pathSeparatorChar, '_');
return s;
}
/**
* Replaces some special characters in filename by '_'.
*/
public static String toFilename(String filename)
{
String s = filename;
s = s.replace(File.separatorChar, '_');
s = s.replace(File.pathSeparatorChar, '_');
return s;
}
/**
* Write all items in <code>c</code> to <code>file</code> using
* serialization.
*/
public static void writeBinary(File file, Collection c) throws IOException
{
logger.debug("writing " + c.size() + " items to binary file: " + file);
ObjectOutputStream out = null;
try {
out = new ObjectOutputStream(new FileOutputStream(file));
out.writeInt(c.size());
for (Iterator i = c.iterator(); i.hasNext();) {
try {
out.writeObject(i.next());
}
catch (NotSerializableException e) {
logger.debug("Object not serializable", e);
}
}
}
finally {
try {
if (out != null) {
out.close();
}
}
catch (IOException e) {
}
}
}
/**
* Writes a text file.
*/
public static void writeText(File file, String text) throws IOException
{
BufferedWriter out = new BufferedWriter(new FileWriter(file));
try {
out.write(text);
}
finally {
try {
out.close();
}
catch (IOException e) {
// this exception gets lost
}
}
}
}
The table below shows all metrics for FileHelper.java.




