Visualizzazione dei risultati da 1 a 3 su 3
  1. #1
    Utente di HTML.it
    Registrato dal
    Feb 2006
    Messaggi
    258

    Inputstream e BufferedReader....aiuto!!!

    Salve ragazzi,
    volevo chiedervi un aiuto per un problema che sto riscontrando.
    Mi è stato chiesto di realizzare una web application in JSF che permetta all'utente di fare l'upload di un file di testo costruito secondo un predefinito formato.
    L'applicazione deve leggere il file,estrarne tramite un'apposita routine java numero di righe e di colonne e visualizzarli all'utente.
    Infine dovrà memorizzare il file in un array di byte secondo un formato interno (sfruttando l'informazione sul numero di righe e di colonne) e inserirlo in un campo blob di un database.
    In un secondo momento con una procedura inversa dovrà estrarre dal blob il file relativo ed eseguirci su opportune query. Questo è cio' che dovrà fare l'applicazione.

    Nello sviluppo di questa applicazione io ho realizzato per ora una miniapplicazione che fa l'upload di un file e ne restituisce il percorso e la lunghezza in byte.
    Inoltre ho già realizzato in passato un'applicazione java che,ricevuto in ingresso un file con formato predefinito, lo memorizza in un contenitore di tipo Map e ne mostra il contenuto.
    Vorrei quindi riutilizzare questa routine java con la mia web application ma non so bene come fare perchè faccio confusione tra il bufferedReader col quale carico il file nella java application e l'inputstream col quale carico il file nella web application.
    Sono ancora inesperto,quindi avrei bisogno di aiuto?
    Avete un pò di pazienza per me?Grazie in anticipo
    La routine java è questa

    /*Il programma funziona correttamente,calcola esattamente numero di righe,di colonne numeriche e di colonne
    usando un contenitore di tipo map(string,array double)*/

    //package gbattine;
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.Map;
    import java.util.StringTokenizer;
    import java.util.HashMap;
    public class AddDb2 {
    private static String fileName = "Dato2.txt";
    private Map <String, double[]>dataMap = null;
    private int Nrows=0;
    private int Ncol=0;
    private int numberOfNumericColumns =0;
    public static void main(String[] args) throws IOException {
    new AddDb2();
    }

    public AddDb2() throws IOException { //constructor
    /* Get a reference to the input file. */
    FileReader file = new FileReader(fileName);
    BufferedReader br = new BufferedReader(file);
    /* Create the empty map. */
    this.dataMap = new HashMap<String, double[]>();/*Constructs an empty HashMap
    with the default initial capacity (16) and the default load factor (0.75).*/
    /* Populate the map from the input file. */
    populateMap(br);
    /*int Dim=(dataMap.size());//include the first string row
    System.out.println("Il size del datamap e'"+Dim);*/
    Ncol=(numberOfNumericColumns+1);
    System.out.println("Il numero di colonne e'"+(Ncol));
    //System.out.println("Il numero di colonne del file è"+dataMap.size());
    /* Display the contents of the map. */
    displayMap(this.dataMap);
    /* Close the reader. */
    br.close();
    }


    /**
    * Populate an HashMap from an input file.
    *
    *

    This method accomodates an input file with any number of lines in
    it. It also accomodates any number of doubles on the input line as long as the
    first value on the line is a String. The number of doubles on each input line can also
    vary.</p>
    *
    * @param bufferedReader
    * @return a Map that has one element for each line of the input file;
    the key is the first column from the input file and the entry is the array
    of doubles that follows the first column
    * @throws IOException
    */
    public Map populateMap(BufferedReader bufferedReader) throws IOException
    {
    System.out.println("Caricamento dell'array di double in corso.....");
    /* Store each line of the input file as a separate key and entry in
    the Map. */
    String line = null;
    while ((line = bufferedReader.readLine()) != null) {
    line = line.replace (',', '.');
    Nrows++;
    /* Create a tokenizer for the line. */
    StringTokenizer st = new StringTokenizer(line);
    /*
    * Assuming that the first column of every row is a String and
    the remaining columns are numbers, count the number of numeric columns.
    */
    //int ColNumber=st.countTokens();
    // int numberOfNumericColumns = ColNumber- 1;
    numberOfNumericColumns = (st.countTokens()-1);
    //System.out.println("Il numero di colonne del file è"+dataMap.size());

    /*
    * Get the first token from the line. It will be a String and
    its value will be a unique key for the rest of the row.
    */
    String key = st.nextToken().trim();
    /* Create the array for the numbers which make up the rest of the line. */
    double[] array = new double[numberOfNumericColumns];
    /* Populate the array by parsing the rest of the line. */
    for (int column = 0; column < numberOfNumericColumns; column++){
    array[column] = Double.parseDouble(st.nextToken().trim());
    }
    /* Store the first column as the key and the array as the entry.
    */
    this.dataMap.put(key, array); /*Associates the specified value with
    the specified key in this map.*/

    }
    System.out.println("Il numero di colonne numeriche del file e'"+numberOfNumericColumns);
    System.out.println("Il numero di righe del file e'"+Nrows);
    //System.out.println("Il numero di colonne del file è"+dataMap.size());
    return this.dataMap;
    }












    public void displayMap(Map<String,double[]> myMap) {
    /* Iterate through the values of the map, displaying each key and
    its corresponding array. */
    for (Map.Entry<String, double[]> entry : myMap.entrySet()) {
    /* Get and display the key. */
    System.out.print(entry.getKey() + " : ");
    /* Get the array. */
    double[] myArray = entry.getValue();
    /*
    * Display each value in the array. Put a semicolon after each
    value except the last.
    * Keep all the values for a given key on a single line.
    */
    for (int ix = 0; ix < myArray.length; ix++) {
    if (ix < myArray.length - 1) { //the value is not the last one in the array ,allora metti ;
    System.out.print(myArray[ix] + "; ");
    } else { //the value is the last one in the array ,la linea finisce così
    System.out.println(myArray[ix]);
    }
    }
    }
    }
    }


    La web application come javabean
    MyBean.java

    package com.devsphere.articles.jsfupload;

    import org.apache.myfaces.custom.fileupload.UploadedFile;

    import javax.faces.application.FacesMessage;
    import javax.faces.context.FacesContext;

    import java.security.MessageDigest;
    //import java.security.NoSuchAlgorithmException;

    import java.io.*;

    public class MyBean {
    private UploadedFile myFile;
    /*private String myParam;
    private String myResult;*/

    public UploadedFile getMyFile() {
    return myFile;
    }

    public void setMyFile(UploadedFile myFile) {
    this.myFile = myFile;
    }

    e come descrittore web.xml

    <?xml version="1.0" encoding="UTF-8"?>

    <!DOCTYPE web-app PUBLIC
    "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd">

    <web-app>

    <context-param>
    <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
    <param-value>client</param-value>
    </context-param>

    <filter>
    <filter-name>ExtensionsFilter</filter-name>
    <filter-class>
    org.apache.myfaces.component.html.util.ExtensionsF ilter
    </filter-class>
    <init-param>
    <param-name>uploadMaxFileSize</param-name>
    <param-value>100m</param-value>
    </init-param>
    <init-param>
    <param-name>uploadThresholdSize</param-name>
    <param-value>100k</param-value>
    </init-param>
    </filter>

    <filter-mapping>
    <filter-name>ExtensionsFilter</filter-name>
    <servlet-name>FacesServlet</servlet-name>
    </filter-mapping>

    <servlet>
    <servlet-name>FacesServlet</servlet-name>
    <servlet-class>
    javax.faces.webapp.FacesServlet
    </servlet-class>
    <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
    <servlet-name>FacesServlet</servlet-name>
    <url-pattern>/faces/*</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
    <servlet-name>FacesServlet</servlet-name>
    <url-pattern>*.faces</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    </web-app>

    e come faces-config.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE faces-config PUBLIC "-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.1//EN"
    "http://java.sun.com/dtd/web-facesconfig_1_1.dtd">
    <faces-config>
    <managed-bean>
    <managed-bean-name>myBean</managed-bean-name>
    <managed-bean-class>com.devsphere.articles.jsfupload.MyBean</managed-bean-class>
    <managed-bean-scope>request</managed-bean-scope>
    </managed-bean>
    <navigation-rule>
    <from-view-id>/pages/MyForm.jsp</from-view-id>
    <navigation-case>
    <from-outcome>success</from-outcome>
    <to-view-id>/pages/MyResult.jsp</to-view-id>
    </navigation-case>
    </navigation-rule>
    </faces-config>


    Grazie

  2. #2
    Utente di HTML.it
    Registrato dal
    Feb 2006
    Messaggi
    258

    Interfacciamento tra streams diversi o cosa?

    Salve ragazzi,
    vorrei chiedervi un aiuto.
    La mia applicazione in JSF fa l'upload di un file di testo tramite un componente di Myfaces per l'upload.
    Volendo effettuare delle operazioni sul file esiste la funzione getInputStream che applicata al file "uploadato" mi restituisce il file come "stream".
    Adesso devo aggiungere all'applicazione una classe java, da me già realizzata, che effettua le modifiche sul file, ma carica il file con un'operazione del genere

    BufferedReader br = new BufferedReader(file);

    e fa le restanti operazioni sempre su br(e non posso cambiare questa classe,quindi devo assolutamente trasportare l'inputstream in un bufferedReader!).
    Mi serve assolutamente trovare un modo per riversare l'inputstream generato da getInputStream in un bufferedReader per usare in maniera trasparente il resto della classe,mi serve cioè questo interfacciamento.
    Come posso farlo?
    Vi prego aiutatemi,non riesco in nessuna maniera ad andare avanti.
    Grazie, se avete idee e pazienza postatemi il codice,non penso sia lungo,sono ancora inesperto...

  3. #3
    Moderatore di Programmazione L'avatar di alka
    Registrato dal
    Oct 2001
    residenza
    Reggio Emilia
    Messaggi
    24,472

    Moderazione

    Ho unito le discussioni in quanto vertono sostanzialmente tutte (come quelle già aperte in precedenza, anche se tollerate) sullo stesso argomento.

    Non aprire più discussioni relative allo stesso problema.
    MARCO BREVEGLIERI
    Software and Web Developer, Teacher and Consultant

    Home | Blog | Delphi Podcast | Twitch | Altro...

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.