FileHelper.java
| Index Score | ||
|---|---|---|
![]() |
![]() |
xnap.util |
![]() |
![]() |
XNap 2 |
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 pure java file sharing client.
*
* See 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; either version 2 of the License, or
* (at your option) any later version.
*
* 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 xnap.util;
import org.apache.log4j.Logger;
import java.io.*;
import java.net.*;
import java.util.*;
/**
* Provides a set of static methods that help with file manipulation.
*/
public class FileHelper
{
private static Logger logger = Logger.getLogger(FileHelper.class);
//--- Method(s) ---
/**
* 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;
}
public static synchronized File createUnique(String path, String filename)
throws IOException
{
File p = new File(path);
if (p.isDirectory() || p.mkdirs()) {
// sanitize filename
filename = filename.replace(File.separatorChar, '_');
return createUnique(path + filename);
}
throw new FileNotFoundException();
}
public static synchronized File moveUnique
(File file, String path, String filename) throws IOException
{
String newFilename = appendSeparator(path) + 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());
}
}
public static synchronized File moveUnique(File file, String path)
throws IOException
{
return moveUnique(file, path, file.getName());
}
/**
* Moves a file. Tries rename first, 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;
}
public static void copy(File source, File dest) throws IOException
{
BufferedInputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new FileInputStream(source));
out = new BufferedOutputStream(new FileOutputStream(dest));
int data;
while ((data = in.read()) != -1) {
out.write(data);
}
}
finally {
if (in != null) {
try {
in.close();
}
catch (IOException e) {
}
}
if (out != null) {
try {
out.close();
}
catch (IOException e) {
}
}
}
}
public static String extension(String filename)
{
int i = filename.lastIndexOf(".");
if (i < 0 || i == filename.length() - 1) {
return "";
}
else {
return filename.substring
(i + 1, filename.length()).toLowerCase();
}
}
public static String extension(String filename, String separator)
{
int i = filename.lastIndexOf(separator);
if (i < 0 || i == filename.length() - 1) {
return "";
}
else {
return filename.substring
(i + 1, filename.length()).toLowerCase();
}
}
public static String getDownloadDirFromExtension(String filename)
{
String ext = extension(filename);
int type = SearchFilterHelper.getMediatypeFromExtension(ext);
Preferences p = Preferences.getInstance();
String dir
= p.getMediaTypeDownloadDir((String)SearchFilter.media[type]);
if (type != SearchFilter.MEDIA_ANYTHING && dir.length() > 0) {
return dir;
}
else {
return p.getDownloadDir();
}
}
public static URL getResource(String filename)
{
return JarClassLoader.getInstance().getResource(filename);
}
public static InputStream getResourceAsStream(String filename)
{
return JarClassLoader.getInstance().getSystemResourceAsStream(filename);
}
public static String name(String filename)
{
int i = filename.lastIndexOf(".");
if (i < 1) {
return filename;
}
else {
return filename.substring(0, i);
}
}
/**
* 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;
}
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(System.getProperty("user.home"));
sb.append(File.separatorChar);
sb.append(".xnap");
sb.append(File.separatorChar);
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 xnap.util.FileHelper#getHomeDir(String)
*/
public static final String getHomeDir()
{
return getHomeDir("");
}
public static String appendSeparator(String dir)
{
if (dir.length() > 0 && !dir.endsWith(File.separator)) {
return dir + File.separator;
}
else {
return dir;
}
}
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) {
}
}
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) {
}
}
}
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 (ClassNotFoundException e) {
logger.warn("error while reading binary file", e);
}
}
}
catch(IOException e) {
throw(e);
}
finally {
try {
if (in != null) {
in.close();
}
}
catch (IOException e) {
}
}
}
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();) {
out.writeObject(i.next());
}
}
catch(IOException e) {
throw(e);
}
finally {
try {
if (out != null) {
out.flush();
out.close();
}
}
catch (IOException e) {
}
}
}
}
The table below shows all metrics for FileHelper.java.




