Java - DataInputStream
DataInputStream viene utilizzato nel contesto di DataOutputStream e può essere utilizzato per leggere le primitive.
Di seguito è riportato il costruttore per creare un InputStream -
InputStream in = new DataInputStream(InputStream in);
Dopo aver in mano l'oggetto DataInputStream , è disponibile un elenco di metodi di supporto, che possono essere utilizzati per leggere il flusso o per eseguire altre operazioni sul flusso.
Sr.No. | Metodo e descrizione |
---|---|
1 | public final int read(byte[] r, int off, int len)throws IOException Legge fino a len byte di dati dal flusso di input in una matrice di byte. Restituisce il numero totale di byte letti nel buffer altrimenti -1 se è alla fine del file. |
2 | Public final int read(byte [] b)throws IOException Legge alcuni byte dal flusso di input e li memorizza nell'array di byte. Restituisce il numero totale di byte letti nel buffer altrimenti -1 se è alla fine del file. |
3 | (a) public final Boolean readBooolean()throws IOException (b) public final byte readByte()throws IOException (c) public final short readShort()throws IOException (d) public final Int readInt()throws IOException Questi metodi leggeranno i byte dall'InputStream contenuto. Restituisce i due byte successivi di InputStream come tipo primitivo specifico. |
4 | public String readLine() throws IOException Legge la riga di testo successiva dal flusso di input. Legge i byte successivi, convertendo ogni byte separatamente in un carattere, finché non incontra un terminatore di riga o la fine del file; i caratteri letti vengono quindi restituiti come una stringa. |
Esempio
Di seguito è riportato un esempio per dimostrare DataInputStream e DataOutputStream. Questo esempio legge 5 righe fornite in un file test.txt e converte quelle righe in lettere maiuscole e infine le copia in un altro file test1.txt.
import java.io.*;
public class DataInput_Stream {
public static void main(String args[])throws IOException {
// writing string to a file encoded as modified UTF-8
DataOutputStream dataOut = new DataOutputStream(new FileOutputStream("E:\\file.txt"));
dataOut.writeUTF("hello");
// Reading data from the same file
DataInputStream dataIn = new DataInputStream(new FileInputStream("E:\\file.txt"));
while(dataIn.available()>0) {
String k = dataIn.readUTF();
System.out.print(k+" ");
}
}
}
Di seguito è riportato un esempio di esecuzione del programma precedente:
Produzione
hello