您的位置:首页 > 编程语言 > Java开发

Java IO实战操作(一)

2012-04-29 22:26 387 查看
/**
* 创建一个新文件
*/
public void NewFiles() {
File file = new File("D:\\IO.txt");
try {
file.createNewFile();
System.out.println("文件创建成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* File类的两个常量\ ;考虑到跨平台性所以推荐使用下面的常量
*/
public void FinalNum() {
System.out.println(File.separator);
System.out.println(File.pathSeparator);
}

/**
* 文件的删除
*/
public void delete() {
String fileName = "D:" + File.separator + "IO.txt";
File file = new File(fileName);
if (file.exists()) {
file.delete();
} else {
System.out.println("文件不存在");
}
}
/**
* 创建一个文件夹
*/
public void Mkdir() {
String fileName = "D:" + File.separator + "IO";
File file = new File(fileName);
file.mkdir();
}

/**
* 列出指定目录下面的全部文件(包括隐藏文件)
*/
public void FileView() {
String fileName = "D:" + File.separator;
File file = new File(fileName);
String[] str = file.list();
File[] fileStr = file.listFiles();// 返回完整路径
for (int i = 0; i < str.length; i++) {
System.out.println(str[i]);
}
}

/**
* 判定一个指定的路径是否为目录
*/
public void TFFile() {
String fileName = "D:" + File.separator;
File file = new File(fileName);
if (file.isDirectory()) {
System.out.println("True");
} else {
System.out.println("False");
}
}

/**
* 列出指定目录的全部内容
*/
public void ViewOver(){
class print{
public void Show(File f){
if(f!=null){
if(f.isDirectory()){
File[] fileArray=f.listFiles();
if(fileArray!=null){
for(int i=0;i<fileArray.length;i++){
// 递归调用
Show(fileArray[i]);
}}}	}}}
String fileName="D:"+File.separator;
File file=new File(fileName);
print pr=new print();
pr.Show(file);}
/**
* 使用RandomAccessFile写入文件
* @throws IOException
*/
public void InserNum() throws IOException {
String fileName = "D:" + File.separator + "IO.txt";
File file = new File(fileName);
RandomAccessFile demo = new RandomAccessFile(file, "rw");
demo.writeBytes("我的天啊。。");
demo.writeInt(12);
demo.writeBoolean(true);
demo.writeChar('A');
demo.writeFloat(1.2f);
demo.writeDouble(12.33);
demo.close();
// 如果你此时打开hello。txt查看的话,会发现那是乱码
}

/**
* 向文件中写入字符串
* @throws IOException
*/
public void StringNum() throws IOException {
String fileName = "D:" + File.separator + "IO.txt";
File file = new File(fileName);
OutputStream out = new FileOutputStream(file);
String str = "你好ACCP";
byte[] Bstr = str.getBytes();
out.write(Bstr);
out.close();
}

/**
* 一个字节一个字节的写入
* @throws IOException
*/
public void OneStringNum() throws IOException {
String fileName = "D:" + File.separator + "IO.txt";
File file = new File(fileName);
OutputStream out = new FileOutputStream(file);
String str = "你好!!";
byte[] Bbyte = str.getBytes();
for (int i = 0; i < Bbyte.length; i++) {
out.write(Bbyte[i]);
}
out.close();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: