创建文件
已有目录下创建文件:
// 已有目录下创建文件:
public class TestFile{
public static void main(String []args){
File file=new File("D:/myDoc/new.txt"); //该目录D:/myDoc已存在;
try{
file.createNewFile(); //核心就是这一句!
}catch(IOException e){
e.printStackTrace();
}
}
}
创建目录+创建文件
// 新建目录和文件需要先创建目录,再创建文件
public class TestFile{
public static void main(String []args){
File file=new File("D:/newfile/new.txt");
Fiel a=file.getParentFile(); //将要新建的文件的父级目录赋给对象a;
a.mkdirs(); //创建父类目录;
try{
file.createNewFile(); //创建文件
}catch( IOException e){
e.printStackTrace;
}
}
}
File类的方法
isDirectory();判断是否是目录;
isFile();判断是否是文件;
length();判断文件长度;
getName();获取文件名字;
file1.renameTo(file2);将file1移动到file2所在的目录下,并命名为file2,相当于移动文件+改名字。
getPath();获取路径;
getAbsolutePath();获取绝对路径;
InputStream类-读文件
读文件方法一:循环挨个字符往外读:
// 新建目录和文件需要先创建目录,再创建文件
public class TestInputStream{
public static void main(String []args){
FileInputStream fis=null;
try{//抛出异常,防止找不到文件;
fis=new FileInputStream("e.txt");//新建InputStream对象
int tmp=0;
while((tmp=fis.read())>0){//每次往外读一个ASCII值,循环直至读完;
System.out.println((char)tmp);//ASCII值转化成字符往外打印;
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally{//最后必须关闭流,用finally是怕中途中断运行不到close()方法;
try{
fish.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
}
读文件方法二:直接读到byte数组中,数组转型为String后输出:
// 新建目录和文件需要先创建目录,再创建文件
public class TestInputStream{
public static void main(String []args){
FileInputStream fis=null;
try{//抛出异常,防止找不到文件;
fis=new FileInputStream("e.txt");//新建InputStream对象
byte[]b=new byte[fis.available()];//新建长度为fis长度的byte型数组;
fis.read(b);//将文件内容读到数组中去;
String s=new Stirng(b);//将byte数组转化成字符;
System.out.println(s);//输出字符串;
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}finally{//最后必须关闭流,用finally是怕中途中断运行不到close()方法;
try{
fish.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
}
OutputStream-写文件
// 新建目录和文件需要先创建目录,再创建文件
public class TestOutputStream{
public static void main(String []args){
FileOutputStream fos=null;
String s="总有一条蜿蜒在童话里的河。";
try{
fos=new FileOutputStream("b.txt");//替换(加,true的话,为追加)
byte[]b=s.getBytes();//将要写的字符串转化为byte数组
fos.write(b);//直接将数组写入文件中;
System.out.println("写入完成");
}catch(IOException e){
e.printStackTrace();
}finally{
try{
fos.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
}