Aller au contenu
immortal

Poster vos class utiles!

Recommended Posts

Bonjour à tous, chers développeurs :)

Il m'est venu une idée après le récent sujet de Knux qui avait besoin d'une méthode assez spécifique de formatage de string.
Mon idée est que nous avons tous des méthodes, des class et des trucs utiles pour nous aider dans notre développement et que nous pourrions tous les partager pour que tout le monde en profite.

Je commence donc avec ma class StringUtils, elle permet de faire de la manipulation de string dans un objet de taille précis, elle permet notamment de faire en sorte qu'un long texte retourne à la ligne quand il dépasse la taille de l'objet.

StringUtils (cette class n'est pas de moi):

import java.awt.FontMetrics;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Globally available utility classes, mostly for string manipulation.
 * 
 * @author Jim Menard, <a href="mailto:jimm@io.com">jimm@io.com</a>
 */
public class StringUtils {
	/**
	 * Returns an array of strings, one for each line in the string after it has
	 * been wrapped to fit lines of <var>maxWidth</var>. Lines end with any of
	 * cr, lf, or cr lf. A line ending at the end of the string will not output a
	 * further, empty string.
	 * <p>
	 * This code assumes <var>str</var> is not <code>null</code>.
	 * 
	 * @param str
	 *          the string to split
	 * @param fm
	 *          needed for string width calculations
	 * @param maxWidth
	 *          the max line width, in points
	 * @return a non-empty list of strings
	 */
	public static List<String> wrap(String str, FontMetrics fm, int maxWidth) {
		List<String> lines = splitIntoLines(str);
		if (lines.size() == 0)
			return lines;

		ArrayList<String> strings = new ArrayList<String>();
		for (Iterator<String> iter = lines.iterator(); iter.hasNext()
			wrapLineInto((String) iter.next(), strings, fm, maxWidth);
		return strings;
	}

	/**
	 * Given a line of text and font metrics information, wrap the line and add
	 * the new line(s) to <var>list</var>.
	 * 
	 * @param line
	 *          a line of text
	 * @param list
	 *          an output list of strings
	 * @param fm
	 *          font metrics
	 * @param maxWidth
	 *          maximum width of the line(s)
	 */
	public static void wrapLineInto(String line, List<String> list, FontMetrics fm, int maxWidth) {
		int len = line.length();
		int width;
		while (len > 0 && (width = fm.stringWidth(line)) > maxWidth) {
			// Guess where to split the line. Look for the next space before
			// or after the guess.
			int guess = len * maxWidth / width;
			String before = line.substring(0, guess).trim();

			width = fm.stringWidth(before);
			int pos;
			if (width > maxWidth) // Too long
				pos = findBreakBefore(line, guess);
			else { // Too short or possibly just right
				pos = findBreakAfter(line, guess);
				if (pos != -1) { // Make sure this doesn't make us too long
					before = line.substring(0, pos).trim();
					if (fm.stringWidth(before) > maxWidth)
						pos = findBreakBefore(line, guess);
				}
			}
			if (pos == -1)
				pos = guess; // Split in the middle of the word

			list.add(line.substring(0, pos).trim());
			line = line.substring(pos).trim();
			len = line.length();
		}
		if (len > 0)
			list.add(line);
	}

	/**
	 * Returns the index of the first whitespace character or '-' in <var>line</var>
	 * that is at or before <var>start</var>. Returns -1 if no such character is
	 * found.
	 * 
	 * @param line
	 *          a string
	 * @param start
	 *          where to star looking
	 */
	public static int findBreakBefore(String line, int start) {
		for (int i = start; i >= 0; --i) {
			char c = line.charAt(i);
			if (Character.isWhitespace(c) || c == '-')
				return i;
		}
		return -1;
	}

	/**
	 * Returns the index of the first whitespace character or '-' in <var>line</var>
	 * that is at or after <var>start</var>. Returns -1 if no such character is
	 * found.
	 * 
	 * @param line
	 *          a string
	 * @param start
	 *          where to star looking
	 */
	public static int findBreakAfter(String line, int start) {
		int len = line.length();
		for (int i = start; i < len; ++i) {
			char c = line.charAt(i);
			if (Character.isWhitespace(c) || c == '-')
				return i;
		}
		return -1;
	}
	/**
	 * Returns an array of strings, one for each line in the string. Lines end
	 * with any of cr, lf, or cr lf. A line ending at the end of the string will
	 * not output a further, empty string.
	 * <p>
	 * This code assumes <var>str</var> is not <code>null</code>.
	 * 
	 * @param str
	 *          the string to split
	 * @return a non-empty list of strings
	 */
	public static List<String> splitIntoLines(String str) {
		ArrayList<String>  strings = new ArrayList<String> ();

		int len = str.length();
		if (len == 0) {
			strings.add("");
			return strings;
		}

		int lineStart = 0;

		for (int i = 0; i < len; ++i) {
			char c = str.charAt(i);
			if (c == '\r') {
				int newlineLength = 1;
				if ((i + 1) < len && str.charAt(i + 1) == '\n')
					newlineLength = 2;
				strings.add(str.substring(lineStart, i));
				lineStart = i + newlineLength;
				if (newlineLength == 2) // skip \n next time through loop
					++i;
			} else if (c == '\n') {
				strings.add(str.substring(lineStart, i));
				lineStart = i + 1;
			}
		}
		if (lineStart < len)
			strings.add(str.substring(lineStart));

		return strings;
	}

}


Un downloader simple de Thog:

import java.io.*;
import java.net.*;
import org.apache.commons.io.FileUtils;

/**
 *
 * @author Thog
 */
public class FileDownloader {
    
    private URL url;
    private File target;
    private long filesize;
    public FileDownloader(URL u, File f)
    {
        this.url = u;
        this.target = f;
        this.filesize = tryGetFileSize(u);
    }
    private int tryGetFileSize(URL url) {
        HttpURLConnection conn = null;
        try {
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("HEAD");
            conn.getInputStream();
            return conn.getContentLength();
        } catch (IOException e) {
            return -1;
        } finally {
            conn.disconnect();
        }
    }
    public void downloadFile()
    {
        boolean needupdate = false;
        String fileName = target.getName();
        if(!target.exists())
        {
            needupdate = true;
            
            try {
                target.getParentFile().mkdirs();
                target.createNewFile();
              
      
            } catch (IOException ex) {
                ex.printStackTrace();
                target.delete();
            }
        }
        else
        {
            long lenght = FileUtils.sizeOf(target);
            if(!(lenght == filesize))
            {
                needupdate = true;
            }
        }
       
        
        if(needupdate)
        {
              InputStream in = null;
        FileOutputStream fout = null;
              try
        {
            in = url.openStream();
            fout = new FileOutputStream(target);

            byte data[] = new byte[1024];
            int count;
            while ((count = in.read(data, 0, 1024)) != -1)
            {
                fout.write(data, 0, count);
            }
        }
        catch(Exception e)
        {
            System.out.println("Cannot download file : " + fileName);
            e.printStackTrace();
             target.delete();
        }
        finally
        {
            if (in != null)
                try
                {
                    in.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                     target.delete();
                }
            if(fout != null)
                try
                {
                    fout.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                     target.delete();
                }
            //System.out.println("File " + fileName + " downloaded successfully");
        }
        }
        
    }
    
}

Un désarchiveur de darkpit58:

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class MyZip{

public static void unzip(File zipfile, File folder) throws FileNotFoundException, IOException{

 
    ZipInputStream zis = new ZipInputStream(
            new BufferedInputStream(new FileInputStream(zipfile.getCanonicalFile())));


    ZipEntry ze = null;
    try {
        while((ze = zis.getNextEntry()) != null){

         
            File f = new File(folder.getCanonicalPath(), ze.getName());
       
           
            if (ze.isDirectory()) {
                f.mkdirs();
                continue;
            }
     
            f.getParentFile().mkdirs();
            OutputStream fos = new BufferedOutputStream(
                    new FileOutputStream(f));
       
            try {
                try {
                    final byte[] buf = new byte[8192];
                    int bytesRead;
                    while (-1 != (bytesRead = zis.read(buf)))
                        fos.write(buf, 0, bytesRead);
                }
                finally {
                    fos.close();
                }
            }
            catch (final IOException ioe) {
               
                f.delete();
                throw ioe;
            }
        }
    }
    finally {
        
        zis.close();
    }
}

}

Utilisation:

MyZip.unzip(new File("dossier ou se trouve l'archive" + "\\nom de larchive.zip/.rar"), new File("dossier d'extraction"));

Une class pour ouvrir une page dans le navigateur par défaut sur Windows et sur les autres système Unix, trouvée par TheShark34 (source perdue):

import java.io.IOException;
 
public class BrowserControl {
 
public static void displayURL(String url) {
boolean windows = isWindowsPlatform();
String cmd = null;
try {
if (windows) {
cmd = WIN_PATH + " " + WIN_FLAG + " " + url;
Runtime.getRuntime().exec(cmd);
} else {
cmd = UNIX_PATH + " " + UNIX_FLAG + "(" + url + ")";
Process p = Runtime.getRuntime().exec(cmd);
try {
int exitCode = p.waitFor();
if (exitCode != 0) {
cmd = UNIX_PATH + " " + url;
p = Runtime.getRuntime().exec(cmd);
}
} catch (InterruptedException x) {
System.err.println("Error bringing up browser, cmd='" + cmd
+ "'");
System.err.println("Caught: " + x);
}
}
} catch (IOException x) {
System.err.println("Could not invoke browser, command=" + cmd);
System.err.println("Caught: " + x);
}
}
 
private static boolean isWindowsPlatform() {
String os = System.getProperty("os.name");
if (os != null && os.startsWith(WIN_ID))
return true;
else
return false;
 
}
 
private static final String WIN_ID = "Windows";
private static final String WIN_PATH = "rundll32";
private static final String WIN_FLAG = "url.dll,FileProtocolHandler";
private static final String UNIX_PATH = "netscape";
private static final String UNIX_FLAG = "-remote openURL";
}

Voilà j'attends avec impatience vos partages si vous en avez à faire :P

A bientôt.

  • Upvote 3

Partager ce message


Lien à poster
Partager sur d’autres sites

Un downloader simple

import java.io.*;
import java.net.*;
import org.apache.commons.io.FileUtils;

/**
 *
 * @author Thog
 */
public class FileDownloader {
    
    private URL url;
    private File target;
    private long filesize;
    public FileDownloader(URL u, File f)
    {
        this.url = u;
        this.target = f;
        this.filesize = tryGetFileSize(u);
    }
    private int tryGetFileSize(URL url) {
        HttpURLConnection conn = null;
        try {
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("HEAD");
            conn.getInputStream();
            return conn.getContentLength();
        } catch (IOException e) {
            return -1;
        } finally {
            conn.disconnect();
        }
    }
    public void downloadFile()
    {
        boolean needupdate = false;
        String fileName = target.getName();
        if(!target.exists())
        {
            needupdate = true;
            
            try {
                target.getParentFile().mkdirs();
                target.createNewFile();
              
      
            } catch (IOException ex) {
                ex.printStackTrace();
                target.delete();
            }
        }
        else
        {
            long lenght = FileUtils.sizeOf(target);
            if(!(lenght == filesize))
            {
                needupdate = true;
            }
        }
       
        
        if(needupdate)
        {
              InputStream in = null;
        FileOutputStream fout = null;
              try
        {
            in = url.openStream();
            fout = new FileOutputStream(target);

            byte data[] = new byte[1024];
            int count;
            while ((count = in.read(data, 0, 1024)) != -1)
            {
                fout.write(data, 0, count);
            }
        }
        catch(Exception e)
        {
            System.out.println("Cannot download file : " + fileName);
            e.printStackTrace();
             target.delete();
        }
        finally
        {
            if (in != null)
                try
                {
                    in.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                     target.delete();
                }
            if(fout != null)
                try
                {
                    fout.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                     target.delete();
                }
            //System.out.println("File " + fileName + " downloaded successfully");
        }
        }
        
    }
    
}

Partager ce message


Lien à poster
Partager sur d’autres sites

Class pour extraire une archive :



import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class MyZip{

public static void unzip(File zipfile, File folder) throws FileNotFoundException, IOException{

 
    ZipInputStream zis = new ZipInputStream(
            new BufferedInputStream(new FileInputStream(zipfile.getCanonicalFile())));


    ZipEntry ze = null;
    try {
        while((ze = zis.getNextEntry()) != null){

         
            File f = new File(folder.getCanonicalPath(), ze.getName());
       
           
            if (ze.isDirectory()) {
                f.mkdirs();
                continue;
            }
     
            f.getParentFile().mkdirs();
            OutputStream fos = new BufferedOutputStream(
                    new FileOutputStream(f));
       
            try {
                try {
                    final byte[] buf = new byte[8192];
                    int bytesRead;
                    while (-1 != (bytesRead = zis.read(buf)))
                        fos.write(buf, 0, bytesRead);
                }
                finally {
                    fos.close();
                }
            }
            catch (final IOException ioe) {
               
                f.delete();
                throw ioe;
            }
        }
    }
    finally {
        
        zis.close();
    }
}

}

Code pour l'itulisé :

MyZip.unzip(new File("dossier ou se trouve l'archive" + "\\nom de larchive.zip/.rar"), new File("dossier d'extraction"));
Modifié par darkpit58

Partager ce message


Lien à poster
Partager sur d’autres sites

a serait quand même cool de citer les sources de vos fichier. En l'occurence http://patatos.over-blog.com/article-decompresser-un-fichier-zip-en-java-44249513.html

D'ailleurs je vous recommande vraiment ce blog http://www.mkyong.com/ y'a pleins de tutos et de classs c''est très instructif

(D'ailleurs verit a raison, pensez a commenter qu'on comprenne ;) )

Partager ce message


Lien à poster
Partager sur d’autres sites

Ce code n'est pas de moi mais je ne me rappelle plus de la source, il permet d'ouvrir une page avec le navigateur par default sur Windows ou n'importe quel système Unix.

import java.io.IOException;

public class BrowserControl {

public static void displayURL(String url) {
boolean windows = isWindowsPlatform();
String cmd = null;
try {
if (windows) {
cmd = WIN_PATH + " " + WIN_FLAG + " " + url;
Runtime.getRuntime().exec(cmd);
} else {
cmd = UNIX_PATH + " " + UNIX_FLAG + "(" + url + ")";
Process p = Runtime.getRuntime().exec(cmd);
try {
int exitCode = p.waitFor();
if (exitCode != 0) {
cmd = UNIX_PATH + " " + url;
p = Runtime.getRuntime().exec(cmd);
}
} catch (InterruptedException x) {
System.err.println("Error bringing up browser, cmd='" + cmd
+ "'");
System.err.println("Caught: " + x);
}
}
} catch (IOException x) {
System.err.println("Could not invoke browser, command=" + cmd);
System.err.println("Caught: " + x);
}
}

private static boolean isWindowsPlatform() {
String os = System.getProperty("os.name");
if (os != null && os.startsWith(WIN_ID))
return true;
else
return false;

}

private static final String WIN_ID = "Windows";
private static final String WIN_PATH = "rundll32";
private static final String WIN_FLAG = "url.dll,FileProtocolHandler";
private static final String UNIX_PATH = "netscape";
private static final String UNIX_FLAG = "-remote openURL";
}

Partager ce message


Lien à poster
Partager sur d’autres sites

Attention dans ton utilitaire darkpit58,java.util.zip.*ne permet que de traité des archives au format zip et uniquement celles ci

Les .jar utilisent le même format de compression que les .zip ;)

Partager ce message


Lien à poster
Partager sur d’autres sites

Sauf que dans son code, il dis "(.zip / .rar)" :/

Oups, j'avais mal compris. En tout cas j'ai testé, et avecjava.util.zip.* j'arrive à unzip des .gz, .zip et .jar

  • Upvote 1

Partager ce message


Lien à poster
Partager sur d’autres sites

Nouvelle class pour télécharger tout les fichiers possibles et inimaginables :P Avec permetant la progression du JProgressBar . Source : www.codejava.net

Premiere class : DownloadTask :

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.swing.JOptionPane;
import javax.swing.SwingWorker;

import fr.thekilleurgamer.launcherv2.HTTPDownloadUtil;
import fr.thekilleurgamer.launcherv2.McPanel;

public class DownloadTask extends SwingWorker<Void, Void> {
	private static final int BUFFER_SIZE = 4096;	
	private String downloadURL;
	private String saveDirectory;
	private McPanel gui;
	
	public DownloadTask(McPanel gui, String downloadURL, String saveDirectory) {
		this.gui = gui;
		this.downloadURL = downloadURL;
		this.saveDirectory = saveDirectory;
	}
	
	/**
	 * Executed in background thread
	 */	
	@Override
	protected Void doInBackground() throws Exception {
		try {
			HTTPDownloadUtil util = new HTTPDownloadUtil();
			util.downloadFile(downloadURL);
			
			
			
			System.out.println(util.getFileName() +  util.getContentLength());
			
			String saveFilePath = saveDirectory + File.separator + util.getFileName();

			InputStream inputStream = util.getInputStream();
			// opens an output stream to save into file
			FileOutputStream outputStream = new FileOutputStream(saveFilePath);

			byte[] buffer = new byte[BUFFER_SIZE];
			int bytesRead = -1;
			long totalBytesRead = 0;
			int percentCompleted = 0;
			long fileSize = util.getContentLength();

			while ((bytesRead = inputStream.read(buffer)) != -1) {
				outputStream.write(buffer, 0, bytesRead);
				totalBytesRead += bytesRead;
				percentCompleted = (int) (totalBytesRead * 100 / fileSize);

				setProgress(percentCompleted);			
			}

			outputStream.close();

			util.disconnect();
		} catch (IOException ex) {
			JOptionPane.showMessageDialog(gui, "Error downloading file: " + ex.getMessage(),
					"Error", JOptionPane.ERROR_MESSAGE);			
			ex.printStackTrace();
			setProgress(0);
			cancel(true);			
		}
		return null;
	}

	/**
	 * Executed in Swing's event dispatching thread
	 */
	@Override
	protected void done() {
		if (!isCancelled()) {
			JOptionPane.showMessageDialog(gui,
					"File has been downloaded successfully!", "Message",
					JOptionPane.INFORMATION_MESSAGE);
		}
	}	
}

Pensez à bien changé les imports suivants :

import fr.thekilleurgamer.launcherv2.HTTPDownloadUtil;
import fr.thekilleurgamer.launcherv2.McPanel;

fr.thekilleurgamer.launcherv2 par votre import et .McPanel par la class ou se trouvera le bouton pour téléchargé .

Deuxieme class : HTTPDownloadUtil :

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HTTPDownloadUtil {

	private HttpURLConnection httpConn;

	/**
	 * hold input stream of HttpURLConnection
	 */
	private InputStream inputStream;

	private String fileName;
	private int contentLength;

	/**
	 * Downloads a file from a URL
	 * 
	 * @param fileURL
	 *            HTTP URL of the file to be downloaded
	 * @throws IOException
	 */
	public void downloadFile(String fileURL) throws IOException {
		URL url = new URL(fileURL);
		httpConn = (HttpURLConnection) url.openConnection();
		int responseCode = httpConn.getResponseCode();

		// always check HTTP response code first
		if (responseCode == HttpURLConnection.HTTP_OK) {
			String disposition = httpConn.getHeaderField("Content-Disposition");
			String contentType = httpConn.getContentType();
			contentLength = httpConn.getContentLength();

			if (disposition != null) {
				// extracts file name from header field
				int index = disposition.indexOf("filename=");
				if (index > 0) {
					fileName = disposition.substring(index + 10,
							disposition.length() - 1);
				}
			} else {
				// extracts file name from URL
				fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
						fileURL.length());
			}

			// output for debugging purpose only
			System.out.println("Content-Type = " + contentType);
			System.out.println("Content-Disposition = " + disposition);
			System.out.println("Content-Length = " + contentLength);
			System.out.println("fileName = " + fileName);

			// opens input stream from the HTTP connection
			inputStream = httpConn.getInputStream();

		} else {
			throw new IOException(
					"No file to download. Server replied HTTP code: "
							+ responseCode);
		}
	}

	public void disconnect() throws IOException {
		inputStream.close();
		httpConn.disconnect();
	}

	public String getFileName() {
		return this.fileName;
	}

	public int getContentLength() {
		return this.contentLength;
	}

	public InputStream getInputStream() {
		return this.inputStream;
	}
}

Et enfin :

String downloadURL = "http://eclipse.ialto.com/technology/epp/downloads/release/luna/R/eclipse-standard-luna-R-win32.zip";
		String saveDir = "C:\\Users\\thekilleurgamer\\Desktop";
		
		try {
			progressBar.setValue(0);

			DownloadTask task = new DownloadTask(this, downloadURL, saveDir);
			task.addPropertyChangeListener(this);
			task.execute();
		} catch (Exception ex) {
			JOptionPane.showMessageDialog(this,
					"Error executing upload task: " + ex.getMessage(), "Error",
					JOptionPane.ERROR_MESSAGE);
		}

Pensez également a changer le contenu des string downloadURL et saveDir .

Et pour terminer :

@Override
	public void propertyChange(PropertyChangeEvent evt) {
		if (evt.getPropertyName().equals("progress")) {
			int progress = (Integer) evt.getNewValue();
			progressBar.setValue(progress);
		}
	}

Et autre chose a modifier , c'est votre implements mettez : implements PropertyChangeListener

Voila c'est tout :P bizz

Partager ce message


Lien à poster
Partager sur d’autres sites

Créer un compte ou se connecter pour commenter

Vous devez être membre afin de pouvoir déposer un commentaire

Créer un compte

Créez un compte sur notre communauté. C’est facile !

Créer un nouveau compte

Se connecter

Vous avez déjà un compte ? Connectez-vous ici.

Connectez-vous maintenant

×