SirSmart Postado Novembro 12, 2015 Denunciar Share Postado Novembro 12, 2015 Galera preciso gravar um arquivo selecionado pelo usuário na pasta do projeto.Gostaria de saber como pego o caminho da pasta do projeto e como gravo nessa pasta Obrigado Citar Link para o comentário Compartilhar em outros sites More sharing options...
0 Oblongs Postado Novembro 20, 2015 Denunciar Share Postado Novembro 20, 2015 Dá uma olhadinha neste código e tente entender. Fiz com imagem, mas acredito que dê para fazer com arquivoLembrando que você pode usar o JFileChooser para pegar o caminho //Metodo para fazer upload de image public void uploadImage(File src,String nomeImg) throws FileNotFoundException{ FileInputStream entrada = new FileInputStream(src); FileOutputStream saida = new FileOutputStream("img_patrimonio/"+nomeImg); int buffer; try { while((buffer = entrada.read()) != -1){ saida.write(buffer); } } catch (IOException ex) { JOptionPane.showConfirmDialog(null,"Erro de buffer!\n"+ex,"Alerta!",JOptionPane.ERROR_MESSAGE); } try { entrada.close(); } catch (IOException ex){ JOptionPane.showConfirmDialog(null,"Erro de entrada!\n"+ex,"Alerta!",JOptionPane.ERROR_MESSAGE); } try { saida.close(); } catch (IOException ex) { JOptionPane.showConfirmDialog(null,"Erro de saída!\n"+ex,"Alerta!",JOptionPane.ERROR_MESSAGE); } }Pegando o caminho public void actionPerformed(ActionEvent e) { JFileChooser teste = new JFileChooser(); FileNameExtensionFilter f = new FileNameExtensionFilter("*jpg","jpg"); teste.setFileFilter(f); teste.showOpenDialog(jpForm); try{ jlbUrlImg.setText(teste.getSelectedFile().toString()); }catch(Exception ex){ System.out.println("Nenhum arquivo selecionado!"); } }Criei um objeto chamado teste e um chamado "f".Teste é o JFileChooser, e "F" é o tipo de arquivo que será lido.teste.getSelectedFile().toString()pega o caminho do arquivo selecionado. Citar Link para o comentário Compartilhar em outros sites More sharing options...
0 Oblongs Postado Novembro 20, 2015 Denunciar Share Postado Novembro 20, 2015 Criei um mini projeto para ficar melhor o entendimento. Obrigado! package mover; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFileChooser; public class MoverArquivo extends javax.swing.JFrame { public MoverArquivo() { initComponents(); } //Metodo que será responsável por enviar o arquivo public void enviarArquivo(File arquivo){ try { //Recebendo o arquivo de entrada FileInputStream entrada = new FileInputStream(arquivo); //Preparando arquivo de saida FileOutputStream saida = new FileOutputStream("teste.zip"); //Variavel para passar os Bytes e montar o arquivo em novo diretorio int b = 0; //Loop responsável pelo envio Byte a Byte while((b = entrada.read()) != -1){ saida.write(b); } //Não esqueça de fechar o envio assim que terminar saida.close(); } catch (FileNotFoundException ex) { Logger.getLogger(MoverArquivo.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(MoverArquivo.class.getName()).log(Level.SEVERE, null, ex); } } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { jbAbrir = new javax.swing.JButton(); jlUrl = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jbAbrir.setText("Abrir"); jbAbrir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbAbrirActionPerformed(evt); } }); jlUrl.setText("URL"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(20, 20, 20) .addComponent(jbAbrir) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jlUrl) .addContainerGap(296, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(45, 45, 45) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jbAbrir) .addComponent(jlUrl)) .addContainerGap(48, Short.MAX_VALUE)) ); pack(); }// </editor-fold> //Acao do botao para abrir o aquivo private void jbAbrirActionPerformed(java.awt.event.ActionEvent evt) { //Criando um objeto do tipo JFileChooser JFileChooser janelaArquivo = new JFileChooser(); //Deixando a janela visivel janelaArquivo.showOpenDialog(this); //Passando para o método criado acima por parametro, já que ele precisa de um arquivo enviarArquivo(janelaArquivo.getSelectedFile()); } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MoverArquivo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MoverArquivo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MoverArquivo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MoverArquivo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new MoverArquivo().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JButton jbAbrir; private javax.swing.JLabel jlUrl; // End of variables declaration } Citar Link para o comentário Compartilhar em outros sites More sharing options...
Pergunta
SirSmart
Galera preciso gravar um arquivo selecionado pelo usuário na pasta do projeto.
Gostaria de saber como pego o caminho da pasta do projeto e como gravo nessa pasta
Obrigado
Link para o comentário
Compartilhar em outros sites
2 respostass a esta questão
Posts Recomendados
Participe da discussão
Você pode postar agora e se registrar depois. Se você já tem uma conta, acesse agora para postar com sua conta.