Fórum Alguém tem uma rotina que Grave/Leia um arquivo em XML ou Texto #391303
25/11/2010
0
Olá boa tarde!
Sou Desenvolvedor de Aplicativos JAVA - (Novato na area)
Estou terminando um trabalha da Faculdade e estou precisando gravar/Ler um arquivo XML ou Texto, usando JAVA (MVC).
Quem puder ajudar, desde já meus agradecimentos.
ANT.CARLOS/SP
Antonio Jesus
Curtir tópico
+ 0
Responder
Posts
25/11/2010
Davi Costa
Antônio Carlos,
obviamente vc vai ter que adaptar para sua necessidade:
public Object getBytesArquivo(ControleGeracaoArquivo c)throws IOException{
InputStream in = null;
try {
c.setNomeArquivo(formata(c.getNomeArquivo(),REGEX_PARCIAL)+".zip");
File arquivo = new File(servicoConf.getPropertiesConf().getProperty(ConstantesProperties.GI000062_PATH)+c.getNomeArquivo());
in = new BufferedInputStream(new FileInputStream(arquivo));
if (arquivo.length() > Integer.MAX_VALUE) throw new IOException("Arquivo grande demais");
byte[] buf = new byte[(int)arquivo.length()];
//Ler os bytes do arquivo
int offset = 0;
int numRead = 0;
while (offset < buf.length
&& (numRead=in.read(buf, offset, buf.length-offset)) >= 0) {
offset += numRead;
}
if (offset < buf.length) throw new IOException("Não pode ler o arquivo completamente");
return buf;
}catch(Exception e){
throw new IOException(e.getMessage());
}finally {
if(in!=null) in.close();
}
}
Outro exemplo:
public byte[] lerArquivo(Anexo anexo) throws ServicoException {
String diretorioRaiz = servicoConf.getPropertiesConf().getProperty(ConstantesProperties.GI000067_ANEXO_DIRETORIO);
InputStream in = null;
try {
File arquivo = new File(diretorioRaiz+anexo.getLocalArquivo());
in = new BufferedInputStream(new FileInputStream(arquivo));
if (arquivo.length() > Integer.MAX_VALUE) throw new IOException("Arquivo grande demais");
byte[] buf = new byte[(int)arquivo.length()];
//Ler os bytes do arquivo
int offset = 0;
int numRead = 0;
while (offset < buf.length
&& (numRead=in.read(buf, offset, buf.length-offset)) >= 0) {
offset += numRead;
}
if (offset < buf.length) throw new IOException("Não pode ler o arquivo completamente");
return buf;
}catch(Exception e){
throw new ServicoException(e);
}finally {
try{
if(in!=null) in.close();
}catch(Exception e){}
}
}
Outro exemplo:
//método para retornar um array de bytes
public Object getBytesArquivo(Object...param)throws IOException{
InputStream in = null;
try {
File arquivo = new File(servicoConf.getPropertiesConf().getProperty(ConstantesProperties.GI000020_PATH)+param[0].toString());
in = new BufferedInputStream(new FileInputStream(arquivo));
if (arquivo.length() > Integer.MAX_VALUE) throw new IOException("Arquivo grande demais");
byte[] buf = new byte[(int)arquivo.length()];
//Ler os bytes do arquivo
int offset = 0;
int numRead = 0;
while (offset < buf.length
&& (numRead=in.read(buf, offset, buf.length-offset)) >= 0) {
offset += numRead;
}
if (offset < buf.length) throw new IOException("Não pode ler o arquivo completamente");
return buf;
}catch(Exception e){
throw new IOException(e.getMessage());
}finally {
if(in!=null) in.close();
}
}
dá uma pesquisada no goolge acredito que vá encontrar bons exemplos.
Att Davi
obviamente vc vai ter que adaptar para sua necessidade:
public Object getBytesArquivo(ControleGeracaoArquivo c)throws IOException{
InputStream in = null;
try {
c.setNomeArquivo(formata(c.getNomeArquivo(),REGEX_PARCIAL)+".zip");
File arquivo = new File(servicoConf.getPropertiesConf().getProperty(ConstantesProperties.GI000062_PATH)+c.getNomeArquivo());
in = new BufferedInputStream(new FileInputStream(arquivo));
if (arquivo.length() > Integer.MAX_VALUE) throw new IOException("Arquivo grande demais");
byte[] buf = new byte[(int)arquivo.length()];
//Ler os bytes do arquivo
int offset = 0;
int numRead = 0;
while (offset < buf.length
&& (numRead=in.read(buf, offset, buf.length-offset)) >= 0) {
offset += numRead;
}
if (offset < buf.length) throw new IOException("Não pode ler o arquivo completamente");
return buf;
}catch(Exception e){
throw new IOException(e.getMessage());
}finally {
if(in!=null) in.close();
}
}
Outro exemplo:
public byte[] lerArquivo(Anexo anexo) throws ServicoException {
String diretorioRaiz = servicoConf.getPropertiesConf().getProperty(ConstantesProperties.GI000067_ANEXO_DIRETORIO);
InputStream in = null;
try {
File arquivo = new File(diretorioRaiz+anexo.getLocalArquivo());
in = new BufferedInputStream(new FileInputStream(arquivo));
if (arquivo.length() > Integer.MAX_VALUE) throw new IOException("Arquivo grande demais");
byte[] buf = new byte[(int)arquivo.length()];
//Ler os bytes do arquivo
int offset = 0;
int numRead = 0;
while (offset < buf.length
&& (numRead=in.read(buf, offset, buf.length-offset)) >= 0) {
offset += numRead;
}
if (offset < buf.length) throw new IOException("Não pode ler o arquivo completamente");
return buf;
}catch(Exception e){
throw new ServicoException(e);
}finally {
try{
if(in!=null) in.close();
}catch(Exception e){}
}
}
Outro exemplo:
//método para retornar um array de bytes
public Object getBytesArquivo(Object...param)throws IOException{
InputStream in = null;
try {
File arquivo = new File(servicoConf.getPropertiesConf().getProperty(ConstantesProperties.GI000020_PATH)+param[0].toString());
in = new BufferedInputStream(new FileInputStream(arquivo));
if (arquivo.length() > Integer.MAX_VALUE) throw new IOException("Arquivo grande demais");
byte[] buf = new byte[(int)arquivo.length()];
//Ler os bytes do arquivo
int offset = 0;
int numRead = 0;
while (offset < buf.length
&& (numRead=in.read(buf, offset, buf.length-offset)) >= 0) {
offset += numRead;
}
if (offset < buf.length) throw new IOException("Não pode ler o arquivo completamente");
return buf;
}catch(Exception e){
throw new IOException(e.getMessage());
}finally {
if(in!=null) in.close();
}
}
dá uma pesquisada no goolge acredito que vá encontrar bons exemplos.
Att Davi
Responder
Gostei + 0
26/11/2010
Davi Costa
Abaixo segue mais um exemplo;
chamada:
importarContatos(new BufferedReader(new InputStreamReader(arquivo.getInputStream())), arquivo.getFilename());
//implementação:
public void importarContatos(BufferedReader conteudoCSV, String nomeArquivo) throws IOException {
int numLinha = 0;
try {
String linha;
boolean cabecalhoEncontrado = false;
//Procura pela linha do cabeçalho que contém o nome dos campos:
while ((linha = conteudoCSV.readLine()) != null) {
numLinha++;
if (linha.equalsIgnoreCase("seu cabeçalho")) {
cabecalhoEncontrado = true;
break;
}
}
if (!cabecalhoEncontrado) {
throw new Exception("Erro ao importar contatos. Arquivo inválido: o cabeçalho contendo o nome dos campos não foi encontrado.");
}
//A linha após o cabeçalho contendo os campos contém os dados
while ((linha = conteudoCSV.readLine()) != null) {
numLinha++;
//Pula a linha caso não possua dados:
if (linha.matches("[ ;]*")) {
continue;
}
//Obtém os atributos da linha:
String[] atributosContato = linha.split(";");
}
} catch (ArrayIndexOutOfBoundsException e) {
throw new Exception("Erro ao importar contato. Formato de arquivo inválido: número de colunas não esperado.");
} catch (ParseException e) {
throw new Exception(String.format("Erro ao importar contato. A linha %d do arquivo possui formato de data inválida.", numLinha));
}
int indiceInicioExtensao = nomeArquivo.toLowerCase().lastIndexOf(".csv");
if (indiceInicioExtensao != -1) {
nomeArquivo = nomeArquivo.substring(0, indiceInicioExtensao);
}
}
Caso tenha resolvido passa o feedBack p gente. Espero ter ajudado
Att Davi
chamada:
importarContatos(new BufferedReader(new InputStreamReader(arquivo.getInputStream())), arquivo.getFilename());
//implementação:
public void importarContatos(BufferedReader conteudoCSV, String nomeArquivo) throws IOException {
int numLinha = 0;
try {
String linha;
boolean cabecalhoEncontrado = false;
//Procura pela linha do cabeçalho que contém o nome dos campos:
while ((linha = conteudoCSV.readLine()) != null) {
numLinha++;
if (linha.equalsIgnoreCase("seu cabeçalho")) {
cabecalhoEncontrado = true;
break;
}
}
if (!cabecalhoEncontrado) {
throw new Exception("Erro ao importar contatos. Arquivo inválido: o cabeçalho contendo o nome dos campos não foi encontrado.");
}
//A linha após o cabeçalho contendo os campos contém os dados
while ((linha = conteudoCSV.readLine()) != null) {
numLinha++;
//Pula a linha caso não possua dados:
if (linha.matches("[ ;]*")) {
continue;
}
//Obtém os atributos da linha:
String[] atributosContato = linha.split(";");
}
} catch (ArrayIndexOutOfBoundsException e) {
throw new Exception("Erro ao importar contato. Formato de arquivo inválido: número de colunas não esperado.");
} catch (ParseException e) {
throw new Exception(String.format("Erro ao importar contato. A linha %d do arquivo possui formato de data inválida.", numLinha));
}
int indiceInicioExtensao = nomeArquivo.toLowerCase().lastIndexOf(".csv");
if (indiceInicioExtensao != -1) {
nomeArquivo = nomeArquivo.substring(0, indiceInicioExtensao);
}
}
Caso tenha resolvido passa o feedBack p gente. Espero ter ajudado
Att Davi
Responder
Gostei + 0
Clique aqui para fazer login e interagir na Comunidade :)