java中操作檔案屬性的一些方法

來源:互聯網
上載者:User

1.當Java.io中,如果檔案的操作的時候,判斷是否隱藏用File.ishiden()

判斷是否唯讀,可用File.canWrite().

2. 當要設定是否是可讀或者是隱藏時,在java中除了提供File.setReadOnly()外,就無其他方法了。

所以我們必須到Dos環境下去設定,在java中用Runtime.getRuntime().exec("attrib " + """ + file.getAbsolutePath()+ """+ " +R")該方法可以實現。因為路徑file.getAbsolutePath()中可能會還有空格,所以必須用引號把它括起來,當作一個參數。這樣就可以實現了

(1)設定唯讀Runtime.getRuntime().exec("attrib " + """ + file.getAbsolutePath()+ """+ " +R");

(2)設定可寫Runtime.getRuntime().exec("attrib " + """ + file.getAbsolutePath()+ """+ " -R");

(3)設定隱藏Runtime.getRuntime().exec("attrib " + """ + file.getAbsolutePath()+ """+ " +H");

(4)設定非隱藏Runtime.getRuntime().exec("attrib " + """ + file.getAbsolutePath()+ """+ " -H");

3.對於讀寫檔案的一些操作原始碼

package fileControl;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.RandomAccessFile;
public class FileControl {
private static String fileName;
private static File file;
public static void main(String[] args){
try {
fileName = "exercise.java";
file = new File("E:" + "\", fileName);
if (file.exists()){
// file.delete();
} else {
file.createNewFile();
}
if (file.isDirectory()){
System.out.println("this file is directory");
}
if (file.isFile()){
System.out.println("this file is a file");
}
FileWriter fw = new FileWriter("E:" + "\" + fileName);
// 緩衝寫入檔案,並且可以通過轉義符或是bw.newLine();來換行
BufferedWriter bw = new BufferedWriter(fw);
// 將字串寫入檔案
bw.write(" 大家好!");
bw.newLine();
bw.write("本?是《JSP?程技巧》");
bw.newLine();
bw.write("?多多指教!");
bw.newLine();
bw.write("email:stride@sina.comqianyf");
bw.flush();
bw.close();
//在檔案制定位置追加內容
RandomAccessFile rf = new RandomAccessFile("E:" + "\" + fileName, "rw");
rf.seek(rf.length());
rf.writeBytes(" zui jia de");
rf.close();
// 通過緩衝來讀檔案
FileReader fr = new FileReader("E:" + "\" + fileName);
BufferedReader br = new BufferedReader(fr);
String lineData = br.readLine();
while (null != lineData){
System.out.println(lineData);
lineData = br.readLine();
}
} catch (IOException ee){
System.out.println("System Exception");
}
}
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.