本文來源于網(wǎng)頁設(shè)計(jì)愛好者web開發(fā)社區(qū)http://www.html.org.cn收集整理,歡迎訪問。 1. 簡要回答文件和流之間的區(qū)別和聯(lián)系。
【解答】
文件(file)和流(stream)即有區(qū)別又有聯(lián)系。文件是在各種媒質(zhì)上(可移動磁盤、硬盤、cd 等)永久存儲的數(shù)據(jù)的有序集合。它是一種進(jìn)行數(shù)據(jù)讀寫操作的基本對象。通常情況下,文件按照樹狀目錄進(jìn)行組織,每個文件都有文件名、文件所在路徑、創(chuàng)建時間、訪問權(quán)限等屬性。
流是字節(jié)序列的抽象概念,例如文件、輸入輸出設(shè)備、內(nèi)部進(jìn)程通信管道或者tcp/ip套接字等均可以看成流。流提供一種向后備存儲器寫入字節(jié)和從后備存儲器讀取字節(jié)的方式。
2. directory類為我們提供了哪些目錄管理的功能,它們是通過哪些方法來實(shí)現(xiàn)的?
【解答】
directory類為我們提供了對磁盤和目錄進(jìn)行管理的功能,如復(fù)制、移動、重命名、創(chuàng)建和刪除目錄,獲取和設(shè)置與目錄的創(chuàng)建、訪問及寫入操作相關(guān)的時間信息。
如:createdirectory方法用于創(chuàng)建指定路徑中的所有目錄;delete方法用于刪除指定的目錄;move方法能夠重命名或移動目錄;exists方法用于確定給定路徑是否引用磁盤上的現(xiàn)有目錄;getcurrentdirectory方法用于獲取應(yīng)用程序的當(dāng)前工作目錄;getfiles方法用于返回指定目錄中的文件的名稱等。
3. 編寫程序綜合應(yīng)用directory類的主要方法。首先確定指定的目錄是否存在,如果存在,則刪除該目錄;如果不存在,則創(chuàng)建該目錄。然后,移動此目錄,在其中創(chuàng)建一個文件,并對文件進(jìn)行計(jì)數(shù)。
【解答】
程序清單如下:
using system;
using system.io;
class test
{
public static void main()
{
string path = @"c:/mydir";
string target = @"c:/testdir";
try
{
if (!directory.exists(path))
{
directory.createdirectory(path);
}
if (directory.exists(target))
{
directory.delete(target, true);
}
directory.move(path, target);
file.createtext(target + @"/myfile.txt");
console.writeline("在{0}中的文件數(shù)目是{1}",
target, directory.getfiles(target).length);
}
catch (exception e)
{
console.writeline("操作失敗: {0}", e.tostring());
}
finally {}
}
}
4. 編寫程序,將文件復(fù)制到指定路徑,允許改寫同名的目標(biāo)文件。
【解答】
程序清單如下:
using system;
using system.io;
class test
{
public static void main()
{
string path = @"c:/temp/mytest.txt";
string path2 = path + "temp";
try
{
using (filestream fs = file.create(path)) {}
file.delete(path2);
file.copy(path, path2);
console.writeline("{0}拷貝到:{1}", path, path2);
file.copy(path, path2, true);
console.writeline("第二次拷貝成功");
}
catch
{
console.writeline("重復(fù)拷貝不允許");
}
}
}
5. 編寫程序,使用file類實(shí)現(xiàn)刪除當(dāng)前目錄下的所有文件。
【解答】
程序清單如下:
using system;
using system.io;
class filetest
{
public static void main()
{
console.writeline("確認(rèn)刪除當(dāng)前目錄下的所有文件?");
console.writeline("點(diǎn)擊'y'鍵繼續(xù),其它鍵取消操作");
int a = console.read();
if(a == 'y' || a == 'y'){
console.writeline("正在刪除文件...");
}
else
{
console.writeline("用戶取消操作");
return;
}
directoryinfo dir = new directoryinfo (".");
foreach (fileinfo f in dir.getfiles())
{
f.delete();
}
}
}