Mes TD de programmation orientée objet (INSA Toulouse)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

FileInfo.java 2.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import java.io.* ;
  2. import java.util.* ;
  3. public class FileInfo {
  4. // No constructor
  5. private FileInfo() { }
  6. /**
  7. * @param path an absolute path to a file or directory
  8. * @return the name of the file or directory
  9. */
  10. public static String getName(String path) {
  11. return (new File(path)).getName() ;
  12. }
  13. /**
  14. * @param path an absolute path to a file
  15. * @return the size of the file
  16. * @throws java.io.IOException if the file does not exist or if it is a directory.
  17. */
  18. public static long size(String path) throws IOException {
  19. File file = new File(path) ;
  20. if (file.exists() && file.isFile()) return file.length() ;
  21. else if (!file.exists ()) throw (new IOException("File " + path + " does not exist.")) ;
  22. else throw (new IOException(path + " is not a regular file.")) ;
  23. }
  24. /**
  25. * @param path an absolute path to a file or a directory
  26. * @return true if it is a directory
  27. */
  28. public static boolean isDirectory(String path) {
  29. return (new File(path)).isDirectory() ;
  30. }
  31. /**
  32. * @param path an absolute path to a file or a directory
  33. * @return true if it is a regular file
  34. */
  35. public static boolean isFile(String path) {
  36. return (new File(path)).isFile() ;
  37. }
  38. /**
  39. * @paral path an absolute path to a directory
  40. * @return an iterator over the paths of all elements in this directory.
  41. * @throws java.io.IOException if it is not a directory.
  42. */
  43. public static Iterator<String> getElements(String path) throws IOException {
  44. File file = new File(path) ;
  45. if (!file.exists ()) throw (new IOException("Directory " + path + " does not exist.")) ;
  46. if (!file.isDirectory()) throw (new IOException(path + " is not a directory.")) ;
  47. String[] elements = file.list() ;
  48. // If the directory could not be read, elements is null here.
  49. if (elements == null) {
  50. elements = new String[0] ;
  51. }
  52. for (int i = 0 ; i < elements.length ; i++) {
  53. elements[i] = path + File.separator + elements[i] ;
  54. }
  55. // if (elements == null) throw (new IOException("Cannot read directory " + path)) ;
  56. return Arrays.asList(elements).iterator() ;
  57. }
  58. }