public class Test { public static void main(String[] args) throws IOException { //声明地址 String path="E:/Test01/"; //声明要创建的文件名 String newfile="1.txt"; //创建一个File实例 File file=new File(path,newfile); //如果E:/Test01/路径下的1.txt文件不存在,那就创建一个1.txt文件 if (!file.exists()){ file.createNewFile(); } } }
下面写文件的写入,文件就用上面所创建的文件,对文件的读写操作可以用
RandomAccessFile(一个类)
public class Test { public static void main(String[] args) throws IOException { //声明地址 String path="E:/Test01/1.txt"; //创建一个实例 RandomAccessFile Raf=new RandomAccessFile(path,"rw"); //定义一个字符串,在写入的时候把它转化为字符写入 String text="大帅哥"; Raf.write(text.getBytes()); //获取已经存在文本长度 int leng= (int) Raf.length(); //在文本后面追加内容要调用seek()方法,可以把光标移动到所输入长度leng的后面 Raf.seek(leng); //定义一个字符串,在写入时候把它转化为字符写入 String text1="是我"; Raf.write(text1.getBytes()); } }
读文件的读取也可以用RandomAccessFile类
public static void main(String[] args) throws IOException { //声明地址 String path="E:/Test01/1.txt"; //创建一个实例 RandomAccessFile Raf=new RandomAccessFile(path,"rw"); //把文本内容存放到一个byte数组当中 byte[] bytes=new byte[(int) Raf.length()]; //读取文本内容 Raf.read(bytes); //利用String构造器把文本内容输出 System.out.println(new String(bytes)); }
下面来举文本或图片的复制
public class Test { public static void main(String[] args) throws IOException { //声明地址 String path="E:/Test01/1.txt"; //声明新的文本或图片 String newpath="E:/Test01/coyp_1.txt"; //创建两个File实例 File file=new File(path); File newFile=new File(newpath); //如果文件coyp_1.txt不存在,就创建 if(!newFile.exists()){ newFile.createNewFile(); //读取旧文本的内容,先创建RandomAccessFile类,利用RandomAccessFile来读取和写入 RandomAccessFile Raf=new RandomAccessFile(file,"rw"); RandomAccessFile newRaf=new RandomAccessFile(newFile,"rw"); //现在开始读取旧文本的内容, byte[] bytes=new byte[(int) Raf.length()]; Raf.read(bytes); //把读取的内容写到新文本当中 newRaf.write(bytes); } } }