基础操作,包括访问文件,创建文件,创建文件夹
package mypackage;
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args)
{
// TODO Auto-generated method stub
File f = new File("E:\\aa.txt");
//创建一个文件对象
System.out.println( "绝对路径为"+f.getAbsolutePath() ); //得到绝对路径
System.out.println(" length: "+f.length()); //得到文件的长度(字节为单位)
System.out.println("是否可读: "+f.canRead()); //是否可读
//创建文件
File ff = new File("aaa.txt");
if( !ff.exists() ) //如果没有存在
{
try
{
ff.createNewFile();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
System.out.println("文件已存在");
}
//创建文件夹
File fff = new File("folder");
if( !fff.exists() )
{
fff.mkdir();
}
else
{
System.out.println("文件夹已存在");
}
}
}
FileInputStream的使用
package mypackage;
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args)
{
// TODO Auto-generated method stub
File f = new File("aaa.txt");
FileInputStream fis = null;
try
{
//因为File没有读写能力,所以需要FileInputStream
fis = new FileInputStream(f);
byte[] b = new byte[1025];
int n = 0; //实际读取得到的字节数
try
{
while( ( n=fis.read(b) ) != -1 ) //没有读到文件结尾
{
String s = new String(b,0,n); //将字节转换为String
System.out.println(s);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
//关闭文件流 *****一定要注意
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
FileOutputStream
package mypackage;
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args)
{
// TODO Auto-generated method stub
File f = new File("test.txt");
//字节输出流
FileOutputStream fos = null;
try {
fos = new FileOutputStream(f);
String s = "12345和\r\n"; //加了一个换行
String s2 = "678";
try {
fos.write( s.getBytes() );
fos.write( s2.getBytes() );
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
//关闭文件流
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}