Manipulação de Arquivos em Java
Manipulação de Arquivos em Java
1/92
Arquivos (cont.)
2/92
Arquivos (cont.)
3/92
Arquivos (cont.)
4/92
Arquivos (cont.)
5/92
Arquivos (cont.)
6/92
Arquivos (cont.)
7/92
Classe File
8/92
Classe File (cont.)
9/92
Classe File (cont.)
10/92
Classe File (cont.)
11/92
[Link]
import java . io . F i l e ;
import java . u t i l . Scanner ;
public class FileDemonstration {
public s t a t i c void analyzePath ( S t r i n g path ) {
F i l e name = new F i l e ( p a t h ) ;
i f ( name . e x i s t s ( ) ) {
System . o u t . p r i n t f ( " %s %s\n %s\n %s\n %s\n %s %s\n
%s %s\n %s %s\n %s %s\n %s %s" ,
name . getName ( ) , " exists " ,
( name . i s F i l e ( ) ? " is a file "
: " is not a file " ) ,
( name . i s D i r e c t o r y ( ) ? " is a directory "
: " is not a directory " ) ,
( name . i s A b s o l u t e ( ) ? " is absolute path "
: " is not absolute path " ) ,
" Last modified : " , name . l a s t M o d i f i e d ( ) ,
" Length : " , name . l e n g t h ( ) ,
" Path : " , name . g e t P a t h ( ) ,
" Absolute path : " , name . g e t A b s o l u t e P a t h ( ) ,
" Parent : " , name . g e t P a r e n t ( ) ) ;
12/92
[Link] (cont.)
13/92
[Link] (cont.)
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
S c a n n e r i n p u t = new S c a n n e r ( System . i n ) ;
System . o u t . p r i n t ( " Enter file or directory name
: " );
analyzePath ( input . nextLine () ) ;
}
14/92
[Link] (cont.)
E n t e r f i l e o r d i r e c t o r y name h e r e : C : \ Program F i l e s \
Java
\ j d k 1 . 6 . 0 \ demo\ j f c
jfc exists
i s not a f i l e
is a directory
i s a b s o l u t e path
L a s t m o d i f i e d : 1162570370359
Length : 0
Path : C : \ Program F i l e s \ J a v a \ j d k 1 . 6 . 0 \ demo\ j f c
A b s o l u t e p a t h : C : \ Program F i l e s \ J a v a \ j d k 1 . 6 . 0 \ demo\ j f c
P a r e n t : C : \ Program F i l e s \ J a v a \ j d k 1 . 6 . 0 \ demo
Directory contents :
CodePointIM
FileChooserDemo
Font2DTest
15/92
[Link] (cont.)
E n t e r f i l e o r d i r e c t o r y name : C : \ Program F i l e s \ J a v a \
j d k 1 . 6 . 0 1 1 \demo\ j f c \ Java2D \README. t x t
README. t x t e x i s t s
is a file
i s not a d i r e c t o r y
i s a b s o l u t e path
L a s t m o d i f i e d : 1228404384270
L e n g t h : 7518
Path : E : \ Program F i l e s \ J a v a \ j d k 1 . 6 . 0 1 1 \demo\ j f c \ Java2D
\README. t x t
A b s o l u t e p a t h : E : \ Program F i l e s \ J a v a \ j d k 1 . 6 . 0 1 1 \demo\
j f c \ Java2D \README. t x t
P a r e n t : E : \ Program F i l e s \ J a v a \ j d k 1 . 6 . 0 1 1 \demo\ j f c \
Java2D
16/92
Arquivos de Texto de Acesso Sequencial
17/92
[Link]
p u b l i c AccountRecord ( ) {
t h i s ( 0 , "" , "" , 0 . 0 ) ;
}
18/92
[Link] (cont.)
p u b l i c i n t getAccount () {
r e t u r n account ;
}
p u b l i c String getFirstName () {
return firstName ;
}
p u b l i c S t r i n g getLastName ( ) {
r e t u r n lastName ;
}
19/92
[Link] (cont.)
p u b l i c v o i d setLastName ( S t r i n g lastName ) {
t h i s . lastName = lastName ;
}
p ub l ic double getBalance () {
return balance ;
}
20/92
Arquivos Texto de Acesso Sequencial
21/92
[Link]
import java . io . FileNotFoundException ;
import java . u t i l . Formatter ;
import java . u t i l . FormatterClosedException ;
import java . u t i l . NoSuchElementException ;
import java . u t i l . Scanner ;
i f ( r e c o r d . getAccount ( ) > 0) {
//grave um novo registro
o u t p u t . f o r m a t ( " %d %s %s %.2f\n" ,
record . getAccount () ,
record . getFirstName () ,
r e c o r d . getLastName ( ) ,
record . getBalance () ) ;
}
else{
System . o u t . p r i n t l n ( " Account number
must be greater than 0" ) ;
}
} 24/92
[Link] (cont.)
catch ( FormatterClosedException e ){
System . e r r . p r i n t l n ( " Error writing to
file " ) ;
return ;
}
catch ( NoSuchElementException e ) {
System . e r r . p r i n t l n ( " Invalid input .
Please try again ." ) ;
i n p u t . n e x t L i n e ( ) ; // descarta a entrada para que
o usuário possa tentar novamente
}
25/92
[Link] (cont.)
public void c l o s e F i l e () {
i f ( o u t p u t != n u l l ) {
output . c l o s e () ;
}
}
}
26/92
Arquivos Texto de Acesso Sequencial
27/92
Arquivos Texto de Acesso Sequencial (cont.)
28/92
[Link]
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
C r e a t e T e x t F i l e app = new C r e a t e T e x t F i l e ( ) ;
app . o p e n F i l e ( ) ;
app . a d d R e c o r d s ( ) ;
app . c l o s e F i l e ( ) ;
}
}
29/92
[Link] (cont.)
To t e r m i n a t e i n p u t , t y p e t h e end−o f − f i l e i n d i c a t o r
when you a r e prompted t o e n t e r i n p u t .
On UNIX/ L i n u x /Mac OS X t y p e < c t r l > d t h e n p r e s s E n t e r
On Windows t y p e < c t r l > z t h e n p r e s s E n t e r
E n t e r a c c o u n t number (> 0 ) , f i r s t name , l a s t name and
balance .
? 100 Bob J o n e s 2 4 . 9 8
E n t e r a c c o u n t number (> 0 ) , f i r s t name , l a s t name and
balance .
? 200 S t e v e Doe −345.67
E n t e r a c c o u n t number (> 0 ) , f i r s t name , l a s t name and
balance .
? 300 Pam White 0 . 0 0
E n t e r a c c o u n t number (> 0 ) , f i r s t name , l a s t name and
balance .
? 400 Sam S t o n e −42.16
E n t e r a c c o u n t number (> 0 ) , f i r s t name , l a s t name and
balance .
? 500 Sue R i c h 2 2 4 . 6 2
E n t e r a c c o u n t number (> 0 ) , f i r s t name , l a s t name and
balance .
? ˆZ
30/92
Leitura de Arquivos de Texto de Acesso Sequencial
31/92
[Link]
public c l a s s ReadTextFile {
p r i v a t e Scanner input ;
32/92
[Link] (cont.)
// lê o registro no arquivo
public void readRecords () {
A c c o u n t R e c o r d r e c o r d = new A c c o u n t R e c o r d ( ) ;
System . o u t . p r i n t f ( " %-10s %-12s %-12s %10s\n" ,
" Account " , " First Name " , " Last Name " , " Balance " ) ;
try {
w h i l e ( i n p u t . hasNext ( ) ) {
record . setAccount ( input . nextInt () ) ;
record . setFirstName ( input . next () ) ;
r e c o r d . setLastName ( i n p u t . next ( ) ) ;
record . setBalance ( input . nextDouble () ) ;
// exibe o conteúdo de registro
System . o u t . p r i n t f ( " %-10d %-12s %-12s
%10.2 f\n" , r e c o r d . g e t A c c o u n t ( ) ,
record . getFirstName () ,
r e c o r d . getLastName ( ) ,
record . getBalance () ) ;
}
}
33/92
[Link] (cont.)
//Se as informações no arquivo não estiverem adequadamente
formatadas
catch ( NoSuchElementException e ) {
System . e r r . p r i n t l n ( " File improperly formed "
);
input . close () ;
System . e x i t ( 1 ) ;
}
//Se Scanner foi fechado antes de os dados serem inseridos
catch ( I l l e g a l S t a t e E x c e p t i o n e ){
System . e r r . p r i n t l n ( " Error reading from file
") ;
System . e x i t ( 1 ) ;
}
}
public void c l o s e F i l e () {
i f ( i n p u t != n u l l )
input . close () ;
}
}
34/92
Arquivos Texto de Acesso Sequencial
35/92
Arquivos Texto de Acesso Sequencial (cont.)
36/92
[Link]
public c l a s s ReadTextFileTest {
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
R e a d T e x t F i l e a p p l i c a t i o n = new R e a d T e x t F i l e ( ) ;
application . openFile () ;
a p p l i c a t i o n . readRecords () ;
application . c l o s e F i l e () ;
}
37/92
Saı́da
38/92
Arquivos Texto de Acesso Sequencial
39/92
Serialização de Objetos
40/92
Serialização de Objetos (cont.)
41/92
Serialização de Objetos (cont.)
42/92
Serialização de Objetos (cont.)
43/92
Serialização de Objetos (cont.)
44/92
Serialização de Objetos (cont.)
45/92
Serialização de Objetos (cont.)
46/92
[Link]
import java . io . FileOutputStream ;
import java . io . IOException ;
import j a v a . i o . ObjectOutputStream ;
import j a v a . u t i l . NoSuchElementException ;
import java . u t i l . Scanner ;
public class CreateSequentialFile
{
//escreve os dados no arquivo
p r i v a t e ObjectOutputStream output ;
// permite que o nome do arquivo seja especificado
public void openFile () {
try {
o u t p u t = new O b j e c t O u t p u t S t r e a m ( new
F i l e O u t p u t S t r e a m ( " clients . ser " ) ) ;
}
catch ( IOException ioException ){
System . e r r . p r i n t l n ( " Error opening file ." ) ;
}
}
47/92
[Link] (cont.)
// adiciona os registros ao arquivo
p u b l i c void addRecords () {
// objeto a ser escrito no arquivo
AccountRecordSerializable record ;
i n t accountNumber = 0 ; // campo numero da conta
S t r i n g f i r s t N a m e ; // campo nome para o objeto
S t r i n g l a s t N a m e ; // campo sobrenome para o objeto
d o u b l e b a l a n c e ; // campo saldo para o objeto
S c a n n e r i n p u t = new S c a n n e r ( System . i n ) ;
System . o u t . p r i n t f ( " %s\n %s" , " Enter account number
(> 0) , first name , last
name and balance ." , "? " ) ;
// repete ate o indicador de final de arquivo
w h i l e ( i n p u t . hasNext ( ) ) {
try {
accountNumber = i n p u t . n e x t I n t ( ) ;
f i r s t N a m e = i n p u t . n e x t ( ) ; // le o nome
l a s t N a m e = i n p u t . n e x t ( ) ; // le o sobrenome
b a l a n c e = i n p u t . n e x t D o u b l e ( ) ; // le o sal
48/92
[Link] (cont.)
i f ( accountNumber > 0 ) {
// cria um novo registro
r e c o r d = new A c c o u n t R e c o r d S e r i a l i z a b l e (
accountNumber , f i r s t N a m e , lastName ,
balance ) ;
// escreve o objeto no arquivo
output . writeObject ( record ) ;
}
else {
System . o u t . p r i n t l n ( " Account number must be
greater than 0. " ) ;
}
}
catch ( IOException ioException ) {
System . e r r . p r i n t l n ( " Error writing to file ." ) ;
return ;
}
49/92
[Link] (cont.)
50/92
[Link] (cont.)
public void c l o s e F i l e () {
try {
i f ( o u t p u t != n u l l )
output . c l o s e () ;
}
catch ( IOException ioException ) {
System . e r r . p r i n t l n ( " Error closing file ." ) ;
System . e x i t ( 1 ) ;
}
}
}
51/92
Serialização de Objetos
52/92
Serialização de Objetos (cont.)
53/92
Leitura: Serialização de Objetos
54/92
Leitura: Serialização de Objetos (cont.)
55/92
[Link]
56/92
[Link] (cont.)
57/92
[Link] (cont.)
58/92
[Link] (cont.)
59/92
Arquivos de Acesso Aleatório
I Atualizáveis.
60/92
Arquivos de Acesso Aleatório (cont.)
61/92
Arquivos de Acesso Aleatório (cont.)
I “r”: leitura;
62/92
Arquivos de Acesso Aleatório (cont.)
63/92
Arquivos de Acesso Aleatório (cont.)
64/92
[Link]
p u b l i c c l a s s Record {
private int id ;
p r i v a t e c h a r itemName [ ] = new c h a r [ 8 0 ] ;
p r i v a t e c h a r d e s c r i p t i o n [ ] = new c h a r [ 2 5 5 ] ;
p u b l i c s t a t i c f i n a l i n t SIZE = 6 7 4 ;
p u b l i c Record ( ) {
t h i s ( 0 , "" , "" ) ;
}
p u b l i c R e c o r d ( i n t i d , S t r i n g itemName , S t r i n g
description ) {
setId ( id ) ;
setItemName ( itemName ) ;
setDescription ( description ) ;
}
65/92
[Link] (cont.)
p ub l ic void writeFixedLengthString ( char f i e l d [ ] ,
String value , i n t s i z e ){
int length = value . length () < size ? value .
l e n g t h ( ) : s i z e −1;
int i ;
f o r ( i = 0 ; i < l e n g t h ; i ++){
f i e l d [ i ] = value . charAt ( i ) ;
}
f i e l d [ i ] = ’\0 ’ ;
}
66/92
[Link] (cont.)
p u b l i c S t r i n g getItemName ( ) {
r e t u r n new S t r i n g ( itemName ) ;
}
p u b l i c v o i d setItemName ( S t r i n g itemName ) {
w r i t e F i x e d L e n g t h S t r i n g ( t h i s . itemName , itemName ,
80) ;
}
67/92
[Link] (cont.)
68/92
[Link]
p u b l i c S t r i n g getItemName ( ) {
r e t u r n itemName ;
}
69/92
[Link] (cont.)
p u b l i c v o i d setItemName ( S t r i n g itemName ) {
t h i s . itemName = itemName ;
}
70/92
[Link] (cont.)
71/92
[Link]
p u b l i c c l a s s RandomAccessFiles {
p r i v a t e s t a t i c v o i d w r i t e R e c o r d ( Record data ) {
RandomAccessFile f i l e = n u l l ;
try {
f i l e = new R a n d o m A c c e s s F i l e ( new F i l e ( "
record . dat " ) , " rw " ) ;
f i l e . s e e k ( d a t a . g e t I d ( ) ∗ R e c o r d . SIZE ) ;
f i l e . w r i t e I n t ( data . g e t I d () ) ;
f i l e . writeUTF ( d a t a . getItemName ( ) ) ;
f i l e . writeUTF ( d a t a . g e t D e s c r i p t i o n ( ) ) ;
}
72/92
[Link] (cont.)
catch ( FileNotFoundException e ){
System . e r r . p r i n t l n ( e . g e t M e s s a g e ( ) ) ;
}
catch ( IOException e ){
System . e r r . p r i n t l n ( e . g e t M e s s a g e ( ) ) ;
}
finally{
i f ( f i l e != n u l l ) {
try {
f i l e . close () ;
}
catch ( IOException e ){
System . e r r . p r i n t l n ( e . g e t M e s s a g e ( ) ) ;
}
}
}
}
73/92
[Link] (cont.)
p r i v a t e s t a t i c Record readRecord ( i n t s i d ) {
RandomAccessFile f i l e = n u l l ;
Record data = n u l l ;
try {
f i l e = new R a n d o m A c c e s s F i l e ( new F i l e ( "
record . dat " ) , " rw " ) ;
f i l e . s e e k ( s i d ∗ R e c o r d . SIZE ) ;
int id = f i l e . readInt () ;
S t r i n g itemName = f i l e . readUTF ( ) ;
S t r i n g d e s c r i p t i o n = f i l e . readUTF ( ) ;
d a t a = new R e c o r d ( i d , itemName , d e s c r i p t i o n ) ;
}
catch ( FileNotFoundException e ){
System . e r r . p r i n t l n ( e . g e t M e s s a g e ( ) ) ;
}
catch ( IOException e ){
System . e r r . p r i n t l n ( e . g e t M e s s a g e ( ) ) ;
}
74/92
[Link] (cont.)
finally{
i f ( f i l e != n u l l ) {
try {
f i l e . close () ;
}
catch ( IOException e ){
System . e r r . p r i n t l n ( e . g e t M e s s a g e ( ) ) ;
}
}
}
r e t u r n data ;
}
75/92
[Link] (cont.)
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
C o l l e c t I n f o c o l = new C o l l e c t I n f o ( ) ;
col . accept () ;
R e c o r d s u e = new R e c o r d ( c o l . g e t I d ( ) ,
c o l . getItemName ( ) ,
col . getDescription () ) ;
writeRecord ( sue ) ;
76/92
[Link] (cont.)
Enter your Id :
12
E n t e r y o u r ItemName
Television
Enter item D e s c r i p t i o n
lcd
12 T e l e v i s i o n l c d
77/92
Outras formas de Leitura e Escrita de Arquivos
78/92
Outras formas de Leitura e Escrita de Arquivos (cont.)
import java . io . File ;
import java . io . FileNotFoundException ;
import java . io . FileOutputStream ;
import java . io . IOException ;
import java . io . PrintWriter ;
import java . u t i l . Scanner ;
catch ( IOException e ){
System . e r r . p r i n t l n ( e ) ;
}
// leitura
try {
S c a n n e r i n = new S c a n n e r ( f i l e ) ;
S t r i n g name = i n . n e x t L i n e ( ) ;
i n t age = i n . n e x t I n t ( ) ;
System . o u t . p r i n t l n ( name + " " + age ) ;
in . close () ;
}
catch ( FileNotFoundException e ){
System . e r r . p r i n t l n ( e ) ;
}
}
80/92
Exemplo 2 de Serialização : [Link]
import java . io . S e r i a l i z a b l e ;
p u b l i c c l a s s Student implements S e r i a l i z a b l e {
p r i v a t e S t r i n g name ;
p r i v a t e double grade ;
p u b l i c Student () {
t h i s ( "" , 0 . 0 ) ;
}
p u b l i c S t u d e n t ( S t r i n g name , d o u b l e g r a d e ) {
t h i s . name = name ;
t h i s . grade = grade ;
}
p u b l i c S t r i n g getName ( ) {
r e t u r n name ;
}
81/92
Exemplo 2 de Serialização : [Link] (cont.)
p u b l i c v o i d setName ( S t r i n g name ) {
t h i s . name = name ;
}
p u b l i c double getGrade () {
return grade ;
}
82/92
[Link]
import java . i o . EOFException ;
import java . io . File ;
import java . io . FileInputStream ;
import java . io . FileNotFoundException ;
import java . io . FileOutputStream ;
import java . io . IOException ;
import java . io . ObjectInputStream ;
import java . i o . ObjectOutputStream ;
import java . u t i l . ArrayList ;
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) t h r o w s
FileNotFoundException , IOException ,
ClassNotFoundException {
F i l e f i l e = new F i l e ( " students . dat " ) ;
A r r a y L i s t <S t u d e n t > s t u d e n t s =new A r r a y L i s t <>() ;
s t u d e n t s . add ( new S t u d e n t ( " Tom " , 7 . 8 ) ) ;
s t u d e n t s . add ( new S t u d e n t ( " Dave " , 6 . 5 ) ) ;
s t u d e n t s . add ( new S t u d e n t ( " Bill " , 5 . 3 ) ) ;
83/92
[Link] (cont.)
// append
//FileOutputStream fo = new FileOutputStream(file,true);
//ObjectOutputStream out = new
AppendableObjectOutputStream(fo);
//serialize
FileOutputStream fo =
new F i l e O u t p u t S t r e a m ( f i l e ) ;
ObjectOutputStream out =
new O b j e c t O u t p u t S t r e a m ( f o ) ;
f o r ( Student s : students ) {
out . w r i t e O b j e c t ( s ) ;
}
out . c l o s e ( ) ;
fo . close () ;
// deserialize
F i l e I n p u t S t r e a m f i = new F i l e I n p u t S t r e a m ( f i l e ) ;
ObjectInputStream in =
new O b j e c t I n p u t S t r e a m ( f i ) ;
A r r a y L i s t <S t u d e n t > s t u d e n t s 2 =
new A r r a y L i s t <>() ;
84/92
[Link] (cont.)
try {
while ( true ){
S t u d e n t tmp = ( S t u d e n t ) i n . r e a d O b j e c t ( ) ;
s t u d e n t s 2 . add ( tmp ) ;
}
}
c a t c h ( EOFException e ) {
}
f o r ( Student s : students2 ) {
System . o u t . p r i n t l n ( s ) ;
}
}
}
85/92
[Link] (cont.)
Tom 7 . 8 0 0 0 0 0
Dave 6 . 5 0 0 0 0 0
B i l l 5.300000
86/92
[Link] (cont.)
Para permitir adicionar mais registros em um arquivo
import java . io . FileOutputStream ;
import java . io . IOException ;
import java . io . ObjectOutputStream ;
import java . io . OutputStream ;
p u b l i c c l a s s AppendableObjectOutputStream extends
ObjectOutputStream {
p u b l i c A p p e n d a b l e O b j e c t O u t p u t S t r e a m ( OutputStream
out ) throws IOException {
super ( out ) ;
}
@Override
protected void writeStreamHeader () throws
IOException {
}
}
87/92
Exemplo 3
public c l a s s JavaBuffered {
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
try {
//FileOutputStream arq = new FileOutputStream(.[Link]”, true);
FileOutputStream arq =
new F i l e O u t p u t S t r e a m ( " arquivo . txt " ) ;
OutputStreamWriter os =
new O u t p u t S t r e a m W r i t e r ( a r q ) ;
B u f f e r e d W r i t e r o u t=new B u f f e r e d W r i t e r ( o s ) ;
88/92
Exemplo 3 (cont.)
try {
FileInputStream arq =
new F i l e I n p u t S t r e a m ( " arquivo . txt " ) ;
InputStreamReader i s =
new I n p u t S t r e a m R e a d e r ( a r q ) ;
B u f f e r e d R e a d e r i n=new B u f f e r e d R e a d e r ( i s ) ;
String linha ;
89/92
Exemplo 3 (cont.)
do {
linha = in . readLine () ;
i f ( l i n h a != n u l l ) {
S t r i n g [ ] p a l a v r a s = l i n h a . s p l i t ( ";" ) ;
System . o u t . p r i n t l n ( "\ nNova linha ------" ) ;
for ( String s : palavras ){
System . o u t . p r i n t ( s + " " ) ;
}
}
} w h i l e ( l i n h a != n u l l ) ;
}
catch ( Exception e ){
System . e r r . p r i n t l n ( " Erro ao escrever o arquivo " ) ;
}
}
}
90/92
Saı́da
Nova l i n h a −−−−−−
36 56 45
Nova l i n h a −−−−−−
46 66 55
Nova l i n h a −−−−−−
56 76 65
91/92