File, Files y Path

public static void main(String[] args) {
		File carpeta = new File("c:\\xampp");
		exploreDirectory(carpeta);
	}
	public static void exploreDirectory(File directory) {
        // Obtiene una lista de los archivos y directorios contenidos en el directorio
        File[] files = directory.listFiles();
        // Recorre cada archivo o directorio
        for (File file : files) {
            if (file.isFile()) {
                // Si es un archivo, imprime su nombre
                System.out.println(file.getName());
            } else if (file.isDirectory()) {
                // Si es un directorio, llama recursivamente al método
                exploreDirectory(file);
            }
        }
    }

	Path path = Paths.get("C:/pepe/ejemplo.jpeg");
		System.out.println(path.getFileName());
		System.out.println(path.getName(0));
		System.out.println(path.getParent());
		System.out.println(path.getRoot());
		 path = Paths.get("archivo.txt");
		 System.out.println(path.getFileName());
			System.out.println(path.getName(0));
			System.out.println(path.getParent());
			System.out.println(path.toAbsolutePath());


public static void main(String[] args) throws IOException {
		Path path = Paths.get("c:\\pepe\\archivo.txt");
		String cadena="o muy bien\n";
		Files.writeString(path, cadena,StandardOpenOption.APPEND );
		ArrayList<String> texto=new ArrayList<>(Arrays.asList("adios","hola","que tal"));
		Files.write(path, texto, StandardCharsets.ISO_8859_1,StandardOpenOption.TRUNCATE_EXISTING);
		try {

			List<String> contenido = Files.readAllLines(path);
			for(String linea:contenido)
			{
				System.out.println(linea);
			}
		} catch (IOException e) {
			System.out.println(e);
		}
	}

public static void main(String[] args) {
		Path path = Paths.get("c:\\pepe\\archivo2.txt");
			ArrayList<String> texto=new ArrayList<>(Arrays.asList("adios","hola","qué tal"));
		try {
			Files.write(path, texto, StandardCharsets.ISO_8859_1,StandardOpenOption.CREATE_NEW);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

public static void main(String[] args) {
		try {
		Path path = Paths.get("c:\\pepe\\archivo.txt");
		List<String> contenido=Files.readAllLines(path,StandardCharsets.ISO_8859_1);
		for(String linea:contenido)
		{
			System.out.println(linea);
		}
		}catch(Exception ex) {
			System.out.println(ex.getMessage());
		}
	}

Publicado por

Avatar del usuario

Juan Pablo Fuentes

Formador de programación y bases de datos