FileWriter
package cn. itcast. p3. io. filereader ;
import java. io. FileWriter ;
import java. io. IOException ;
public class LIANXI {
private static final String LINE_SEPARATOR = System . getProperty ( "line_separator" ) ;
public static void main ( String [ ] args) throws IOException {
FileWriter fw = new FileWriter ( "a.txt" , true ) ;
fw. write ( "abc" + LINE_SEPARATOR+ "def" ) ;
fw. flush ( ) ;
fw. close ( ) ;
}
}
FileReader
package cn. itcast. p3. io. filereader ;
import java. io. FileNotFoundException ;
import java. io. FileReader ;
import java. io. IOException ;
public class LIANXI {
public static void main ( String [ ] args) throws IOException {
FileReader fr = new FileReader ( "demo.txt" ) ;
int ch = 0 ;
while ( ( ch= fr. read ( ) ) != - 1 ) {
System . out. println ( ( char ) ch) ;
}
fr. close ( ) ;
}
}
IOException
package cn. itcast. p3. io. filereader ;
import java. io. FileWriter ;
import java. io. IOException ;
public class LIANXI {
private static final String LINE_SEPARATOR = System . getProperty ( "line_separator" ) ;
public static void main ( String [ ] args) {
FileWriter fw = null ;
try {
fw= new FileWriter ( "demo.txt" , true ) ; } catch ( IOException e) { e. printStackTrace ( ) ;
}
try { fw. write ( "abc" + LINE_SEPARATOR+ "efg" ) ; } catch ( IOException e) { e. printStackTrace ( ) ;
}
if ( fw!= null )
try {
fw. close ( ) ;
}
catch ( IOException e) { throw new RuntimeException ( "关闭失败!" ) ; }
} }
FileReader容器写法
package cn. itcast. p3. io. filereader ;
import java. io. FileNotFoundException ;
import java. io. FileReader ;
import java. io. IOException ;
public class LIANXI {
public static void main ( String [ ] args) throws IOException {
FileReader fr = new FileReader ( "demo.txt" ) ;
char [ ] buf = new char [ 1024 ] ;
int len = 0 ;
while ( ( len= fr. read ( buf) ) != - 1 ) {
System . out. println ( new String ( buf, 0 , len) ) ;
}
}
}