This shows you the differences between two versions of the page.
Both sides previous revision Previous revision Next revision | Previous revision Next revision Both sides next revision | ||
java:read_from_file [2016/03/26 05:29] gthanos [Διαβάζοντας δυαδικά δεδομένα από αρχείο] |
java:read_from_file [2017/02/17 11:10] gthanos [Διαβάζοντας δυαδικά δεδομένα από αρχείο] |
||
---|---|---|---|
Line 169: | Line 169: | ||
* Η μέθοδος διαβάζει το πολύ //b.length// bytes. | * Η μέθοδος διαβάζει το πολύ //b.length// bytes. | ||
* Επιστρέφει τον αριθμό των bytes που διάβασε. | * Επιστρέφει τον αριθμό των bytes που διάβασε. | ||
+ | |||
+ | ==== Παράδειγμα διαβάσματος από δυαδικό αρχείο ==== | ||
+ | |||
+ | <code java ReadBinFile.java> | ||
+ | import java.io.*; | ||
+ | import java.util.*; | ||
+ | |||
+ | public class ReadBinFile { | ||
+ | public static void main(String [] args) { | ||
+ | | ||
+ | Scanner sc = new Scanner(System.in); | ||
+ | System.out.print("Enter filename: "); | ||
+ | String readFilename = sc.next(); | ||
+ | File readFile = new File(readFilename); | ||
+ | | ||
+ | if( !readFile.isFile() ) { | ||
+ | System.err.println("Input file does not exist or is not a regular file!"); | ||
+ | return; | ||
+ | } | ||
+ | if( !readFile.canRead() ) { | ||
+ | System.err.println("Input file is not readable!"); | ||
+ | return; | ||
+ | } | ||
+ | | ||
+ | try { | ||
+ | byte []buffer = new byte[2048]; | ||
+ | FileInputStream in = new FileInputStream(readFile); | ||
+ | int read_len; | ||
+ | while( (read_len = in.read(buffer)) != -1 ) { | ||
+ | | ||
+ | } | ||
+ | | ||
+ | in.close(); | ||
+ | } catch( IOException ex ) { | ||
+ | ex.printStackTrace(); | ||
+ | } | ||
+ | } | ||
+ | } | ||
+ | </code> | ||
+ | |||
+ | |||
+ | |Προηγούμενο: [[ java:class_file | Η κλάση File ]] | [[ :toc | Περιεχόμενα ]] | Επόμενο: [[ :java:write_to_file | Γράφοντας σε αρχείο]] | | ||
+ | |||
+ | |||