In Java we have two types of approaches to the files: consider them as entities (ie files and directories) or treated as content (ie Writer and Reader).
file management as an entity is exclusively via the File object, its allow manufacturers to refer to physical paths (existing or not) and its methods enable you to read directories, create empty files or directories, delete files or directories (empty), rename file or directory: File f =
new File ("folder"), / / \u200b\u200bpoint to a file on the file system
if (! f.exists ())
f.mkdir () / / create the directory
innerFile File = new File (f, "file.txt");
innerFile.createNewFile();
f.delete(); //non funziona, ritorna false
if (f.isDirectory() && f.listFiles().length > 0) innerFile.renameTo(new File("." + File.separatorChar + "test.txt"));
f.delete () / / now works
These indicators are all methods that are used for the examination, and usually in real life.
classes on writing and reading of the file contents are divided into Writer / OutputStream and Reader / InputStream; the difference between Writer and OutputStream is that it works on characters while working on the second byte.
important to remember that System.in is an InputStream, and is a System.out PrintWriter;
For certification does not need to know the Stream , but are required if you want to use the console and you do not want to use the Console class.
classes we use are:
FileWriter (accepts a File or a String) and provides methods write (), flush (), close () .
BufferedWriter (Writer accepts a) and provides as FileWriter plus newLine ().
PrintWriter (takes File, String, Writer and OutputStream) and provides the methods also FileWriter and format () , printf () , print () , println () .
FileReader (accepts a File or a String) and provides read () .
BufferedReader (accepts a Reader) and provides read () and readLine () ;
Una classe che può essere utile conoscere (non per la certificazione, ma per se stessi) è InputStreamReader ; questa classe è un Reader , e accetta un InputStream ; in pratica fa da ponte tra i due sistemi e permette di usare BufferedReader su oggetti InputStream (che sono quasi tutti quelli restituiti dai flussi: System.in, Socket, Servlet, ...).
La lettura (da file, da flusso, da console) si può ottenere usando:
BufferedReader brF = new BufferedReader(new FileReader("nomefile.txt"));
BufferedReader brs = new BufferedReader (new InputStreamReader (socket.getInputStream ())); / / socket is here for example, does not exist in the context
BufferedReader brc = new BufferedReader (new InputStreamReader (System.IO in));
so you can use brF.readLine () ; since readLine returns null when the flow ends, you can use the construct common
String res;
while ((res = brF.readLine ())! = null) {/ * Do something with res * /}
Writing (anywhere, or on file in append mode) is obtained using:
PrintWriter PWF = new PrintWriter ("filename.txt ");
PrintWriter pwFA = new PrintWriter (new FileWriter (" filename.txt ", true));
pws = new PrintWriter PrintWriter (socket.getOutputStream ()) ; / / socket is here for example, does not exist in the context
then you write using pwF.println ("hello world "); or pwF.format ("% d that has value? ", 123);
is important to remember that if you close the stream and especially if you are not the flush () after wrote you may not actually send the data.
Using Console allows you to use keyboard and monitor for output, and in some cases you do not have a Console (see Using Eclipse) and in that case you must implement the code by hand to read from keyboard, otherwise we can use code like the following:
System.Console Console c = ();
if (c! = null) {
System.out.println ("Give me your username:");
; c.readLine username = String ();
System.out.println ("Now give me the password:");
char [] pw = c.readPassword ();
System.out.println ("Your username is" + username);
System. out.print ("Your password");
System. out.print ("Your password");
for (char ch: pw)
; c.format ("% c", ch);
c.format ("\\ n");
}
dealing read a line from the keyboard, read a password (using the characters because strings are immutable in Java, and would not be wise to use an immutable object in a pool and to store a password) and then use the format method whereas, using the syntax that is also found in C ( printf ) allows you to print formatted strings.
Finally we have Java classes that handle the serialization. An object is said
Serializable if it implements the interface Serializable . The usefulness stems from the fact that you can write that instance as a stream of bytes, and you can send via Stream, or write to files, or embed it on a database, the classes we use are:
DataInputStream / DataOutputStream - provide methods to read and write primitive data strings or UTF;
FileInputStream / FileOutputStream - provide ways to access files as a stream of bytes (and not stream of characters);
ObjectInputStream / ObjectOutputStream - allow you to read and write primitive data and objects,
Finally we have Java classes that handle the serialization. An object is said
Serializable if it implements the interface Serializable . The usefulness stems from the fact that you can write that instance as a stream of bytes, and you can send via Stream, or write to files, or embed it on a database, the classes we use are:
DataInputStream / DataOutputStream - provide methods to read and write primitive data strings or UTF;
FileInputStream / FileOutputStream - provide ways to access files as a stream of bytes (and not stream of characters);
ObjectInputStream / ObjectOutputStream - allow you to read and write primitive data and objects,
Here are some examples of these objects:
System.out.println ("Enter a number between 1 and 100");
DataInputStream dis = new DataInputStream (System.in);
dis.readInt int value = ();
System.out.println (value);
example trarvi of code that could mislead, since readInt () does not behave as we might think, does not take a line, converts it to an integer and returns, but rather the law of 4 bytes and returns an integer value with those bytes, this code might be as an application, then we must learn the logic required;
Grandpa class implements Serializable {
public String name;}
.. .
Grandpa Grandpa n = new ();
n.nome = "foo";
new ObjectOutputStream (new FileOutputStream ("date. txt ")). writeObject (n);
...
Grandpa writes the instance of the specified file "data.txt" in binary format, to get back the data you should do the reverse:
n = (Grandfather) new ObjectInputStream (new FileInputStream ("data.txt")). readObject ();
Serialization is a process complex and cumbersome for the system, since each object must be serialized for every variable, until you have only primitive types.
The following code throws exception java.io.NotSerializableException on line writeObject
NonnoNonSerializabile class implements Serializable {
public String nome;
public Object surname;
}
...
NonnoNonSerializabile n = new NonnoNonSerializabile();
n.nome = "pippo";
n.surname = new Object();
new ObjectOutputStream(new FileOutputStream("data.txt")).writeObject(n);
...
I problemi con la serializzazione iniziano quando non abbiamo modo di rendere tutte le classi serializzabili; in quel caso possiamo solo rendere transient il campo colpevole, e implementare a mano il codice:
private void writeObject(ObjectOutputStream os) {
// codice per salvare il soprannome del nonno
}
private void readObject(ObjectInputStream is) {
// codice per leggere il soprannome e memorizzarlo sul nonno
}
così si risolve il problema delle classi non Serializable;
Dettagli importanti sulla serializzazione sono:
- le variabili statiche non vengono mai serializzate.
- se in una gerarchia di classi una classe non è serializabile, quando si restores the object will be calling the constructor of that class (and all the fathers);
- not serialize objects must be marked transient (or receive an exception)
- serialize arrays are, but must also be their content
0 comments:
Post a Comment