Fórum Ler arquivo .txt e transformar seu conteúdo em Array #568360
16/12/2009
0
Johnny Ribeiro
Curtir tópico
+ 0Posts
17/12/2009
Johnny Ribeiro
Gostei + 0
17/12/2009
Johnny Ribeiro
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
/**
*
*/
public class Esbosso {
public static void main(String[] args) {
String nomeArquivo = null;
String nomeArquivoCompleto = "C:\\Temp\\Esbosso\\src\\Contatos.txt";
nomeArquivo = nomeArquivoCompleto;
FileInputStream fin = null;
BufferedReader in = null;
String linha = null;
int qtddLinhas = 0;
String[] contatos = new String[qtddLinhas];
try {
fin = new FileInputStream(nomeArquivo);
in = new BufferedReader(new InputStreamReader(fin));
// IOException
while (in.ready()) {
// IOException
linha = in.readLine();
if (linha == null) {
break;
}
linha = linha.trim();
if (linha.length() != 0) {
System.out.println(linha);
qtddLinhas++;
}
}
System.out.println("Linhas: " + qtddLinhas);
// IOException
fin.close();
// IOException
in.close();
} catch (FileNotFoundException e) {
System.out.println("Arquivo não encontrado ...");
System.exit(1);
} catch (IOException e) {
System.out.println("Erro durante a leitura do arquivo ...");
System.exit(1);
}
}
}Gostei + 0
17/12/2009
Johnny Ribeiro
int qtddLinhas = 0; String[] contatos = new String[qtddLinhas];
List<String> linhas = new ArrayList<String>();
...
while (...) {
...
System.out.println(linha);
linhas.add(linha);
qtddLinhas++; // desnecessario
...
}
String[] contatos = linhas.toArray(new String[linhas.size()]);
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
/**
*
*/
public class Esbosso {
public static void main(String[] args) {
String nomeArquivo = null;
String nomeArquivoCompleto = "C:\\Temp\\Esbosso\\src\\Contatos.txt";
nomeArquivo = nomeArquivoCompleto;
FileInputStream fin = null;
BufferedReader in = null;
String linha = null;
int qtddLinhas = 0;
String[] contatos = new String[qtddLinhas];
try {
fin = new FileInputStream(nomeArquivo);
in = new BufferedReader(new InputStreamReader(fin));
// IOException
while (in.ready()) {
// IOException
linha = in.readLine();
if (linha == null) {
break;
}
linha = linha.trim();
if (linha.length() != 0) {
System.out.println(linha);
qtddLinhas++;
}
}
System.out.println("Linhas: " + qtddLinhas);
// IOException
fin.close();
// IOException
in.close();
} catch (FileNotFoundException e) {
System.out.println("Arquivo não encontrado ...");
System.exit(1);
} catch (IOException e) {
System.out.println("Erro durante a leitura do arquivo ...");
System.exit(1);
}
}
}Gostei + 0