Java

Deserialize an object from a file

	/**
	 * Deserialize an object from a file
	 * 
	 * @param in
	 *            an input stream.
	 * 
	 * @return the deserialized object.
	 * 
	 * @throws IOException
	 *             if an I/O exception occured.
	 */
	public static Object deserialize(File file) throws IOException {
		BufferedInputStream in = new BufferedInputStream(new FileInputStream(
				file));
		ObjectInputStream oin = new ObjectInputStream(in);

		try {
			return oin.readObject();
		} catch (ClassNotFoundException ex) {
			throw new IOException(ex.getMessage());
		} finally {
			if (oin != null) {
				oin.close();
			}
		}
	}

 

Serialize a serializable object to a file.

	/**
	 * Serialize an object to a file.
	 * 
	 * @param o
	 *            a serializable object.
	 * @param out
	 *            the stream to write the object to.
	 * 
	 * @throws IOException
	 */
	public static void serialize(Object o, File file) throws IOException {
		BufferedOutputStream out = new BufferedOutputStream(
				new FileOutputStream(file));
		ObjectOutputStream oout = new ObjectOutputStream(out);

		try {
			oout.writeObject(o);
		} finally {
			if (oout != null) {
				oout.close();
			}
		}
	}
 

Read the contents from the given text file

/**
	 * Read the contents from the given text file.
	 * 
	 * @param file
	 *            text file to be read.
	 * 
	 * @return contents of the give file.
	 * 
	 * @throws IOException
	 *             if an I/O error occured.
	 */
	public static String readTextFile(File file,String encoding) throws IOException {
		BufferedReader in = null;

		try {
			if (!file.exists()) {
				throw new IOException("File not exist");
			}

			in = new BufferedReader(new InputStreamReader(new FileInputStream(
					file), encoding /* NOI18N */));

			int fileSize = (int) file.length();

			char[] buf = new char[fileSize];
			in.read(buf, 0, fileSize);

			return new String(buf);
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException ignored) {
					;
				}
			}
		}
	}
 

Delete the given file or directory

   /**
     * Delete the given file or directory.
     *
     * @param file a file or directory.
     * @param recursive if true directories will be deleted recursively.
     *
     * @return true if the file or directory could be deleted successfully.
     */
    public static boolean delete(
        File    file,
        boolean recursive)
    {
        if (file.exists())
        {
            if (file.isFile())
            {
                return file.delete();
            }
            if (recursive)
            {
                File[] files = file.listFiles();
                boolean success = false;

                for (int i = 0; i < files.length; i++)
                {
                    if (files[i].isDirectory() && (files[i].list().length != 0))
                    {
                        success = delete(files[i], true);
                    }
                    else
                    {
                        success = files[i].delete();
                    }

                    if (!success)
                    {
                        return false;
                    }
                }

                return file.delete();
            }
            return file.delete();
        }
        return false;
    }
 

Copy the given file to a new folder

/**
	 * Copy the given file to a new folder
	 * 
	 * @param source
	 *            source file.
	 * @param destination
	 *            destination file.
	 * @param overwrite
	 *            if true the destination file will be always
	 *            overwritten if it already exists; if false it
	 *            will only be overwritten if the source file is newer than the
	 *            destination file.
	 * 
	 * @return Returns true if the file was sucessfully copied
	 * 
	 * @throws IOException
	 *             if an I/O error occured.
	 * @throws NullPointerException
	 *             if source == null
	 * @throws IllegalArgumentException
	 *             if source does not exist or does not denote a file.
	 */
	public static boolean file(File source, File destination, boolean overwrite)
			throws IOException {
		if (source == null) {
			throw new NullPointerException();
		}

		if (!source.exists()) {
			throw new IllegalArgumentException("Source is not found!");
		}

		if (!source.isFile()) {
			throw new IllegalArgumentException("Source is not a file.");
		}

		if (overwrite || (destination.lastModified() < source.lastModified())) {
			// ensure that parent directory of destination file exists
			File parent = destination.getAbsoluteFile().getParentFile();

			if ((parent != null) && !parent.exists()) {
				parent.mkdirs();
			}

			InputStream in = new BufferedInputStream(
					new FileInputStream(source));
			OutputStream out = new BufferedOutputStream(new FileOutputStream(
					destination));
			byte[] buffer = new byte[8 * 1024];
			int count = 0;

			try {
				do {
					out.write(buffer, 0, count);
					count = in.read(buffer, 0, buffer.length);
				} while (count != -1);
			} finally {
				if (in != null) {
					in.close();
				}

				if (out != null) {
					out.close();
				}
			}

			return true;
		}

		return false;
	}
 

Copy the given directory to a new location

/**
	 * Copy the given directory to a new location.
	 * 
	 * @param source
	 *            the directory to copy.
	 * @param destination
	 *            the destination directory.
	 * 
	 * @return true if the operation ended upon success.
	 * 
	 * @throws IOException
	 *             if an I/O error occured.
	 * @throws NullPointerException
	 *             if source == null
	 * @throws IllegalArgumentException
	 *             if source does not exist or does not denote a
	 *             directory.
	 */
	public static boolean directory(File source, File destination)
			throws IOException {
		if (source == null) {
			throw new NullPointerException();
		}

		if (!source.exists()) {
			throw new IllegalArgumentException("Source is not found");
		}

		if (!source.isDirectory()) {
			throw new IllegalArgumentException("Source is not a directory");
		}

		File[] files = source.listFiles();
		boolean success = true;

		for (int i = 0; i < files.length; i++) {

			if (files[i].isFile()) {
				success = file(files[i], new File(destination, files[i]
						.getName()), false);
			} else {
				success = directory(files[i], new File(destination, files[i]
						.getName()));
			}

			if (!success) {
				return false;
			}
		}

		return success;

	}

 

Page 1 of 2

«StartPrev12NextEnd»