Tem como saber em Java a estrutura de diretórios do sistema?
Por exemplo, a partir do meu C: , ter como listar todos os diretórios e
arquivos presentes?
Alguma coisa relacionada a System?
Valew!!!
Tem como saber em Java a estrutura de diretórios do sistema?
Por exemplo, a partir do meu C: , ter como listar todos os diretórios e
arquivos presentes?
Alguma coisa relacionada a System?
Valew!!!
Mas eu gostaria de listar também subdiretórios e arquivos dentro de subdiretórios.
Essa é minha dúvida.
valew…
Dá pra vc fazer isso usando recursividade. Tipo, vc usa um dos vários métodos que retornam File[], itera sobre esse array, e pra cada referência de File que vc tem na mão, faz a mesma coisa recursivamente. Entendeu?
[]'s
coisa do tipo:
File file = new File("C:\projetos");
File [] list = file.listFiles();
for(int i=0; i<list.length; i++) {
System.out.println(list[i].getName());
File [] list2 = list[i].listFiles();
for(int j=0; j<list.length; j++) {
System.out.println(" " + list2[j].getName());
}
}
Nesse código ele somente vai até o 2º nível de diretório.
Queria todos. :lol:
Para listar somente os subdiretorios, utilize um FileFilter:
public Teste(){
List diretorios = Arrays.asList(new File("c:\projeto").listFiles(
new FileFilter(){
public boolean accept(File pathname){
return pathname.isDirectory();
}
}
));
for(Iterator i=diretorios.iterator();i.hasNext();){
System.out.println(i.next());
}
}
É exatamente o q fiz, mas vc utilizou List ao invés de Array.
E… ?
Rafael
Esse programa abaixo faz o seguinte : Vc entra com o nome de diretorio e ele lista os arquivos nesse diretorio. Mas se nesse diretorio que vc deu como entrada contiver subdiretorios ele tb listara os arquivos desse subdiretorio e assim sucessivamente, de maneira recursiva. Para fazer o que vc quer bastar mandar listar alem dos arquivos , istar tb os subdiretorios.
/*
/**
*
@author lindeberg
/
import java.io.;
import javax.swing.*;
import java.util.ArrayList;
public class Pesquisa extends javax.swing.JFrame {
static int i,t=0;
static String output = “”, maior="";
static File aux [];
static long max;
public Pesquisa() {
initComponents();
setSize(500,600);
}
public static void Directory(File conteudo)
{
output += ("<DIR> "+ conteudo + "
");
File subvet [];
File file [];
ArrayList fileArray = new ArrayList();
subvet = conteudo.listFiles();
for(int w = 0;w < subvet.length; w++)
{
if (subvet[w].isFile())
{
output += (subvet[w].getName() + "
");
fileArray.add(subvet[w]);
//file[t] = subvet[w];
}
}
file = (File[])fileArray.toArray();
t = file.length;
for(int v = 0;v < t;v++)
{
max = file[v].length();
if (v +1 <= file.length && file[v +1].length() >= max)
{
max = subvet[v+1].length();
maior = subvet[v+1].getName();
}
}
output += ("O maior é : " + maior+ "Tamanho : "+ max + "
");
for( int j=0 ; j < subvet.length ; j++ ){
if (subvet[j].isDirectory()){
Directory(subvet[j]);
}
// if (subvet[j].isFile()){//aqui eh a logica da comparação dos arquivos
// output += (subvet[j].getName() + "
");
// }
} //fim do for
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
raiz = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
local = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
saida = new javax.swing.JTextArea();
jButton1 = new javax.swing.JButton();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
getContentPane().setLayout(null);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
exitForm(evt);
}
});
jLabel1.setText("Diretu00f3rio rau00edz ");
getContentPane().add(jLabel1);
jLabel1.setBounds(30, 80, 140, 15);
getContentPane().add(raiz);
raiz.setBounds(190, 80, 180, 19);
jLabel2.setText(" Localizau00e7u00e3o do diretorio");
getContentPane().add(jLabel2);
jLabel2.setBounds(10, 130, 160, 15);
getContentPane().add(local);
local.setBounds(190, 130, 180, 19);
saida.setEditable(false);
jScrollPane1.setViewportView(saida);
getContentPane().add(jScrollPane1);
jScrollPane1.setBounds(80, 270, 380, 200);
jButton1.setText("Mostra");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
getContentPane().add(jButton1);
jButton1.setBounds(290, 170, 77, 25);
jLabel3.setText("u00c1rvore de Diretorios");
getContentPane().add(jLabel3);
jLabel3.setBounds(60, 230, 140, 15);
jLabel4.setFont(new java.awt.Font("Dialog", 3, 18));
jLabel4.setText("trabalho");
getContentPane().add(jLabel4);
jLabel4.setBounds(300, 20, 160, 15);
pack();
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String caminho;
int w;
caminho = local.getText();
File nomeFile = new File(caminho);
if (!nomeFile.exists() || !nomeFile.isDirectory()){
JOptionPane.showMessageDialog(this,"Digite apenas Diretoios");
}
else
{
Directory(nomeFile);
}
saida.setText(output);
}
/** Exit the Application */
private void exitForm(java.awt.event.WindowEvent evt) {
System.exit(0);
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
new Pesquisa().show();
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextField local;
private javax.swing.JTextField raiz;
private javax.swing.JTextArea saida;
// End of variables declaration
}
Valew pessoal,
consegui fazer…
não conhecia muito esse esquema de recursividade, legal.
Pra quem quiser, ae vai um exemplo, bem simples.
Coloque na variável path, o diretório a partir do qual você quer começar a busca.
package rascunho;
import java.io.File;
public class ListaArquivosDiretorios {
public ListaArquivosDiretorios() {
}
public void listar(File path) {
File [] files = path.listFiles();
for(int i=0; i<files.length; i++) {
if (files[i].isFile())
System.out.println(" " + files[i].getName());
else
System.out.println(files[i].getName());
if (files[i].isDirectory()){
listar(files[i]);
}
}
}
public static void main(String args[]) {
String path = "O diretorio a partir de onde quer listar";
ListaArquivosDiretorios instance = new ListaArquivosDiretorios();
instance.listar(new File(path));
}
}
Valew!!!
Nao foi exatamente nao … Eu coloquei um FileFilter, para q soh venham diretorios… Daih, vc nao tem q tratar dentro do Loop
Beleza…
Valew cara, obrigado!