本文目錄一覽:
怎樣使用java編程實現文件的剪切/移動
可以通過BufferedReader
流的形式進行流讀取,之後通過readLine方法獲取到的內容,之後通過if判斷來實現在某些特定位置的內容的剪切和移動操作。
舉例:
BufferedReader
bre
=
null;
OutputStreamWriter
pw
=
null;//定義一個流
try
{
String
file
=
“D:/test/test.txt”;
bre
=
new
BufferedReader(new
FileReader(file));//此時獲取到的bre就是整個文件的緩存流
pw
=
new
OutputStreamWriter(new
FileOutputStream(“D:/test.txt”),”GBK”);//確認流的輸出文件和編碼格式,此過程創建了“test.txt”實例
while
((str
=
bre.readLine())!=
null)
//
判斷最後一行不存在,為空結束循環
{
if(str.indexOf(“排除”)0){//判斷是否需要捨棄
pw.write(str);//將要寫入文件的內容,可以多次write
}
}
bre.close();//關閉流
pw.close();//關閉流
解釋:以上方法是實現的刪除,if中的條件改變下,即可實現其餘的功能。
備註:文件流用完之後必須及時通過close方法關閉,否則會一直處於打開狀態,直至程序停止,增加系統負擔。
Java怎麼移動文件夾里的文件到指定文件
是的,用File類的renameTo方法即可,注意目標文件名一定要合法,否則失敗!
/**
* 移動文件到指定目錄
*
* @param oldPath
* String 如:c:/fqf.txt
* @param newPath
* String 如:d:/fqf.txt
*/
public static void moveFile(String oldPath, String newPath) {
copyFile(oldPath, newPath);
delFile(oldPath);
}
/**
* 移動文件到指定目錄
*
* @param oldPath
* String 如:c:/fqf.txt
* @param newPath
* String 如:d:/fqf.txt
*/
public static void moveFolder(String oldPath, String newPath) {
copyFolder(oldPath, newPath);
delFolder(oldPath);
}
Java中如何進行文件(及文件夾)的新建,移動,刪除等?給出代碼
File
F=new
File(路徑);/通過將給定路徑名字符串轉換為抽象路徑名來創建一個新
File
實例。
F.delete();//刪除此抽象路徑名表示的文件或目錄。
文件的移動的話,得通過輸入輸出流
FileInputStream
FI=new
FileInputStream(F);
FileOutputStream
FO=new
FileOutputStream(F);
wile(FI.read()!=EOF)
{
FO.write();
}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/162646.html