File
File類用于封裝一個文件路徑,可以描述一個文件或文件夾姻檀,通過File對象可以讀取文件或者文件夾的屬性數(shù)據(jù)命满,但是讀取文件的內容,就需要使用IO流技術绣版。
構造函數(shù)
public static void demo() {
File file = new File("E:/Demo");
File file1 = new File("E:", "Demo1");
File file2 = new File(file, "Test");
}
創(chuàng)建
public static void demo() throws IOException {
String filePath = "E:/Demo/Test";
File file = new File(filePath);
file.mkdir();//創(chuàng)建單級文件夾胶台,"E:/Demo"
file.mkdirs(); //創(chuàng)建多級文件夾,"E:/Demo/Test"
file.createNewFile();//創(chuàng)建文件杂抽,"E:/Demo/Test.txt"
}
刪除
public static void demo() {
String filePath = "E:/Demo";
File file = new File(filePath);
file.delete();
file.deleteOnExit();
}
重命名
public static void demo() {
File file1 = new File("E:", "Demo");
file1.mkdir();
File file2 = new File("E:", "Changed");
file1.renameTo(file2); //重命名
}
判斷
public static void demo() {
File file = new File("E:", "Demo");
boolean exists = file.exists(); //判斷文件是否存在
boolean directory = file.isDirectory(); //判斷是否為文件夾
boolean file1 = file.isFile();//判斷是否為文件
boolean hidden = file.isHidden();//判斷文件是否隱藏
boolean absolute = file.isAbsolute();//判斷是否為絕對路徑
}
獲取
public static void demo() {
File file = new File("E:", "Demo");
file.mkdir();
String name = file.getName();
String path = file.getPath();
String absolutePath = file.getAbsolutePath();
String parent = file.getParent();
long length = file.length();
long lastModified = file.lastModified();
Date date = new Date(lastModified);
SimpleDateFormat format = new SimpleDateFormat("yyyy年HH月dd日 hh:MM:ss");
System.out.println(format.format(date));
}
文件夾相關
public static void demo() {
File file = new File("E:", "Demo");
file.mkdir();
String[] list = file.list();//獲取當前文件夾下的所有子文件與子文件夾名
File[] files = file.listFiles();//獲取當前文件夾下的所有子文件與子文件夾
}
IO流
OutputStream(字節(jié)輸出流)
FileOutputStream(字節(jié)輸出流)
public static void write(File file) {
try (
//如果目標文件不存在诈唬,會自動創(chuàng)建目標文件對象
//如果目標文件已經存在,會先清空目標文件中的數(shù)據(jù)然后再寫入數(shù)據(jù)
//FileOutputStream fos = new FileOutputStream(file)
//如果目標文件已存在缩麸,想要追加數(shù)據(jù)铸磅,使用此構造方法
FileOutputStream fos = new FileOutputStream(file, true)
) {
String str = "Demo write data";
//雖然接收的是一個int類型的數(shù)據(jù),但是真正寫出的只是一個字節(jié)的數(shù)據(jù)
//只是把低八位的二進制數(shù)據(jù)寫出杭朱,其他二十四位數(shù)據(jù)全部丟棄
fos.write(str.getBytes());
fos.flush();
System.out.println("寫入成功");
} catch (IOException e) {
e.printStackTrace();
}
}
BufferedOutputStream(緩沖字節(jié)輸出流)
public static void write(File file) {
try (
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
) {
String str = "Demo write data";
//先把數(shù)據(jù)寫到它內部維護的字節(jié)數(shù)組中
bos.write(str.getBytes());
//如果真正寫到硬盤上就需要調用它的flush阅仔,或close方法
// 或者內部維護的字節(jié)數(shù)據(jù)已經填滿數(shù)據(jù)的時候也會刷出去
bos.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
InputStream(字節(jié)輸入流)
FileInputStream(字節(jié)輸入流)
public static void read(File file) {
try (
FileInputStream fis = new FileInputStream(file)
) {
//用于聲明文件讀取到那里
int len;
// 建立緩沖字節(jié)數(shù)組,大小一般用1024倍數(shù)弧械,理論上越高效率越高
byte bur[] = new byte[1024];
// 如果使用read傳入字節(jié)數(shù)組八酒,那么數(shù)據(jù)是存儲到字節(jié)數(shù)組的,
// 返回值是存儲到緩沖數(shù)組中字節(jié)個數(shù),-1為結束
while ((len = fis.read(bur)) != -1) {
System.out.println(new String(bur, 0, len));
}
} catch (IOException e) {
e.printStackTrace();
}
}
BufferedInputStream(緩沖字節(jié)輸入流)
public static void read(File file) {
try (
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis)
) {
int len;
// BufferedInputStream本身是不具備讀寫文件能力
// 需要借助FileInputStream來讀取文件的數(shù)據(jù)
while ((len = bis.read()) != -1) {
System.out.println((char) len);
}
// 關閉調用BufferedInputStream.close()實際是調用FileInputStream.close()
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Writer(字符輸出流)
FileWriter(字符輸出流)
public static void write(File file) {
try (
FileWriter writer = new FileWriter(file, true)
) {
String str = "Demo write data";
// 內部維護了一個1024個字符數(shù)組的梦谜,寫數(shù)據(jù)的時候會先寫入它內部維護的字符數(shù)組中丘跌,
// 如果需要把數(shù)據(jù)真正寫到硬盤袭景,需要調用flush或者close或者是填滿內存的字符數(shù)組。
writer.write(str);
writer.flush();
System.out.println("寫入成功");
} catch (IOException e) {
e.printStackTrace();
}
}
BufferedWriter(緩沖字符輸出流)
public static void write(File file) {
try (
FileWriter writer = new FileWriter(file, true);
BufferedWriter bw = new BufferedWriter(writer);
) {
String str = "Demo write data";
bw.write(str);
bw.flush();
bw.close();
System.out.println("寫入成功");
} catch (IOException e) {
e.printStackTrace();
}
}
Reader(字符輸入流)
FileReader(字符輸入流)
public static void read(File file) {
try (
FileReader reader = new FileReader(file);
) {
int len;
char buf[] = new char[1024];
while ((len = reader.read(buf)) != -1) {
System.out.println(new String(buf, 0, len));
}
} catch (IOException e) {
e.printStackTrace();
}
}
BufferedReader(緩沖字符輸入流)
public static void read(File file) {
try (
FileReader reader = new FileReader(file);
BufferedReader br = new BufferedReader(reader);
) {
String len = null;
while ((len = br.readLine()) != null) {
System.out.println(len);
br.lines();
}
} catch (IOException e) {
e.printStackTrace();
}
}
InputStreamReader闭树,OutputStreamWriter(轉換流)
將字節(jié)流轉換為字符流
public static void demo(File file) {
try (
FileOutputStream fos = new FileOutputStream(file, true);
FileInputStream fis = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos))
) {
String str = "Demo write data";
bw.write(str);
bw.flush();
String len;
while ((len = br.readLine()) != null) {
System.out.println(len);
}
} catch (IOException e) {
e.printStackTrace();
}
}
SequenceInputStream(合并流)
public static void split() {
//目標文件
File goalFile = new File("E:", "Demo/Demo.mp3");
//結果文件
File resultFile = new File("E:", "Demo/Split");
try (
FileInputStream fis = new FileInputStream(goalFile);
) {
int len;
byte bur[] = new byte[1024 * 1024];
for (int i = 1; (len = fis.read(bur)) != -1; i++) {
FileOutputStream fos = new FileOutputStream(
new File(resultFile, "split" + i + ".mp3"));
fos.write(bur, 0, len);
fos.flush();
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void merge() {
//碎片所在文件夾
File goalFile = new File("E:", "Demo/Split");
File[] files = goalFile.listFiles(); //獲取文件下所有文件
Vector<FileInputStream> vector = new Vector<>();
for (File item : files) {
//判斷是否為MP3格式
if (item.getName().endsWith(".mp3")) {
try {
vector.add(new FileInputStream(item));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Enumeration<FileInputStream> elements = vector.elements();
SequenceInputStream sis = new SequenceInputStream(elements);
File resultFile = new File("E:", "merge.mp3");
try (
FileOutputStream fileOutputStream = new FileOutputStream(resultFile);
) {
byte buf[] = new byte[1024];
int len;
while ((len = sis.read(buf)) != -1) {
fileOutputStream.write(buf, 0, len);
}
fileOutputStream.flush();
sis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
PrintStream(打印流)耸棒,DataOutputStream(數(shù)據(jù)流)
PrintStream(打印流)
- 可以打印任何類型的數(shù)據(jù),而且打印數(shù)據(jù)之前都會先把數(shù)據(jù)轉換成字符串报辱,再進行打印的与殃。
- 收集異常的日志信息。
public static void demo() throws FileNotFoundException {
try (PrintStream printStream = new PrintStream(
new File("E:", "Demo.txt"))) {
printStream.println();//通過此函數(shù)打印任何數(shù)據(jù)
} catch (FileNotFoundException e) {
PrintStream printStream = new PrintStream(
new File("E:", "Demo.txt"));
e.printStackTrace(printStream); //打印到指定文本
}
}
DataOutputStream(數(shù)據(jù)流)
public static void demo() throws IOException {
File file = new File("E:/Demo.txt");
//寫入
DataOutputStream dos = new DataOutputStream(
new FileOutputStream(file));
dos.writeUTF("通過Write方法碍现,寫入任何數(shù)據(jù)");
//讀取
DataInputStream dis = new DataInputStream(new FileInputStream(file));
String readUTF = dis.readUTF();
System.out.println("需要對應讀取" + readUTF);
}
內存流
所謂內存流幅疼,是將信息暫時存儲在內存中。
內存流本身就是內存中的資源昼接,流中的內容也是內存中的資源爽篷,理論上是不用關閉流,內存也會將其釋放慢睡,但是最好還是手動關一下逐工。
public static void demo() throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write("Demo".getBytes());
//從內存中拿出
byte[] buf = baos.toByteArray();
ByteArrayInputStream bais = new ByteArrayInputStream(buf);
int len;
byte resBuf[] = new byte[1024];
while ((len = bais.read(resBuf)) != -1) {
System.out.println(new String(resBuf, 0, len));
}
bais.close();
}
PipedInputStream(管道流)
管道流用于線程間的通信
PipedInputStream
PipedOutputStream
PipedReader
PipedWriter
//A線程發(fā)送數(shù)據(jù)給B線程
class AThread extends Thread {
PipedOutputStream pipedOutput = new PipedOutputStream();
public PipedOutputStream getPipedOutput() {
return pipedOutput;
}
@Override
public void run() {
try {
for (int i = 65; i < 65 + 26; i++) {
pipedOutput.write(i);
}
pipedOutput.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//B線程接收A發(fā)送的數(shù)據(jù)
class BThread extends Thread {
PipedInputStream pipedInput;
//需要將管道流連接才能通信,由此piped的流構造方法允許傳入對應管道流
public BThread(AThread aThread) throws IOException {
pipedInput = new PipedInputStream(aThread.getPipedOutput());
}
@Override
public void run() {
int len = 0;
try {
while ((len = pipedInput.read()) != -1) {
System.out.println((char) len);
}
pipedInput.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
IO異常處理
傳統(tǒng)方式處理IO異常
public class Run {
public static void main(String[] args) {
copy();
}
public static void copy() {
// 目標拷貝文件路徑
File file = new File("D:" + File.separator + "Test.txt");
// 存放路徑
File file2 = new File("E:" + File.separator + "Test.txt");
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
try {
fileInputStream = new FileInputStream(file);
fileOutputStream = new FileOutputStream(file2);
int len = 0;
byte[] bur = new byte[1024];
while ((len = fileInputStream.read(bur)) != -1) {
fileOutputStream.write(bur, 0, len);
}
} catch (IOException e) {
// 首先終止代碼,然后通知調用者出現(xiàn)問題
// 把IOException傳遞給RuntimeException包裝一層漂辐,讓調用者使用更加靈活
System.out.println("讀取資源出錯");
throw new RuntimeException(e);
} finally {
try {
// 關閉資源原則
// 先開后關
// 后開先關
if (fileOutputStream != null) {
fileOutputStream.close();
System.out.println("關閉輸出流資源成功");
}
} catch (IOException e) {
System.out.println("關閉輸出流資源出錯");
throw new RuntimeException(e);
} finally {
try {
if (fileInputStream != null) {
fileInputStream.close();
System.out.println("關閉輸入流資源成功");
}
} catch (IOException e) {
System.out.println("關閉輸入流資源出錯");
throw new RuntimeException(e);
}
}
}
}
}
AutoCloseable處理IO異常
JDK1.7提供了AutoCloseable接口來自動關閉資源泪喊,從源碼體系上看InputStream實現(xiàn)了Closeable接口,而Closeable接口為AutoCloseable的子類髓涯。
public static void demo(){
try(
//打開資源代碼
){
//可能出現(xiàn)異常的代碼
//讀寫操作
}catch (IOException e) {
throw new RuntimeException(e);
}
}
public static void demo() {
File file = new File("D:" + File.separator + "Test.txt");
try (
FileInputStream fileInputStream = new FileInputStream(file);
) {
byte[] buf = new byte[1024];
int len = 0;
while ((len = fileInputStream.read(buf)) != -1) {
System.out.println(new String(buf, 0, len));
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}