1、通過File類中的createNewFile()創建一個新的文件
/**
* 測試創建文件
* @throws IOException
*/
@Test
public void testCreateFile() throws IOException{
File file = new File("E:/desc.txt");
if(!file.exists()){
file.createNewFile();
}
}
2、創建文件夾
public void testCreatePath(){
File file = new File("E:/abcd");
if(!file.exists()){
System.out.println("目錄不存在,自動創建");
file.mkdirs();
}
}
注意:mkdirs()方法的使用,在路徑只有一級路徑時用mkdir()或者mkdirs()都可以,當有多級路徑(E:\abc\test),時只能使用mkdirs()方法
3、讀取一個文件
public void testReadFile() throws IOException{
File file = new File("E:/desc.txt");
if(!file.exists()||file.isDirectory()){
throw new FileNotFoundException();
}
BufferedReader bf = new BufferedReader(new FileReader(file));
String line = null;
StringBuffer sb = new StringBuffer();
while((line = bf.readLine()) != null){
sb.append(line+" ");
line = bf.readLine();
}
System.out.println(sb);
}
4、在文件中寫入內容
public void testBufferedWrite(){
try {
BufferedWriter bfw = new BufferedWriter(new FileWriter("E:\\demo.txt"));
bfw.write("this is my java !");
bfw.flush();
bfw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
5、復制文件
public void testCopyFile() throws IOException{
//創建輸入流對象
FileInputStream in = new FileInputStream("E:/test.txt");
File file = new File("E:/desc.txt"); //為判斷文件是否存在
if(!file.exists()){
System.out.println("文件不存在");
file.createNewFile();
}
FileOutputStream out = new FileOutputStream(file);
int c;
byte buffer[]=new byte[1024];
while((c = in.read(buffer)) != -1){
for(int i=0;i<c;i++){
out.write(buffer[i]);
}
}
in.close();
out.close();
}