IO流——檔案的基本操作
阿新 • • 發佈:2018-12-31
基本操作
包括檔案的建立、刪除、寫入、讀取
建立檔案和資料夾
// 建立檔案和資料夾
@Test
public void test1() throws Exception
{
File file = new File("F:"+File.separator+"booway"+File.separator+"Java"+File.separator+"0711"+File.separator+"TestFile");
File file2 = new File("TestFile");// 在專案的根目錄下建立
// 判斷是否存在
if (!file.exists ())
{
file.mkdirs();
file.createNewFile();
file2.mkdirs();
file2.createNewFile();
}
}
#
// 刪除檔案
@Test
public void test2() throws Exception
{
String path = "F:"+File.separator+"booway"+File.separator+"Java"+File.separator+"0711"+File.separator+"test.txt" ;
File file = new File(path);
file.deleteOnExit();// 虛擬機器關閉後才刪除檔案
}
向檔案中寫內容
// 寫檔案
@Test
public void test4() throws Exception
{
String path = "F:"+File.separator+"booway"+File.separator+"Java"+File.separator+"0711"+File.separator+"TestFile";
File file = new File(path);
// 覆蓋新增
// FileOutputStream outputStream = new FileOutputStream(file);
// 追加新增
FileOutputStream outputStream = new FileOutputStream(file, true);
for (int i = 0; i < 100; i++)
{
outputStream.write("hello world".getBytes());
}
// 清除快取
outputStream.flush();
// 關閉流
outputStream.close();
}
讀取檔案內容
@Test
public void test5() throws Exception
{
String path = "F:"+File.separator+"booway"+File.separator+"Java"+File.separator+"0711"+File.separator+"TestFile";
File file = new File(path);
FileInputStream inputStream = new FileInputStream(file);
byte[] b = new byte[1024];
int len = 0;
int temp = 0;
while ((temp = inputStream.read()) != -1)
{
b[len] = (byte) temp;
len++;
}
inputStream.close();
System.out.println(new String(b));
}
遍歷資料夾下第一級檔案或資料夾
@Test
public void test6()
{
String path = "F:"+File.separator+"booway"+File.separator+"Java"+File.separator+"0711"+File.separator+"test";
File file = new File(path);
File[] files = file.listFiles();
for (File file2 : files)
{
System.out.println(file2);
}
}