package chapter6;
import java.io.*;
public class IOClass {
//-------File类的使用--------
////1.使用createNewFile()创建文件
public void createForFile(){
Boolean isNewFile =false;
File file =new File("haha.txt");//仅仅只创建了一个文件名
System.out.println("1:"+file.exists());//1.查询这个具有这个文件名的文件存在吗?
try {//I/O操作天生具有风险,注意捕捉异常
isNewFile =file.createNewFile();//创建文件,注意返回值是Boolean类型的
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("2:"+isNewFile);//2.
System.out.println("3:"+file.exists());//3.
//outPut is:(注意第一次和第二次的运行结果是不一样的,因为开始并没有haha.txt)
//1:false
//2:true
//3:true
}
////2.使用mkdir()创建目录
public void createForDirectory(){
File myDir =new File("D:\\cy");//注意这里需要2个"\",一个用来转义
myDir.mkdir();
File myFile =new File(myDir,"new.txt");
try {
myFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
////3.delete()和rename()的使用
public void delAndRenameAndFind(){
File myDir =new File("D:\\cy");
if(!myDir.isDirectory()){
myDir.mkdir();
}
File file1 =new File(myDir,"new1.txt");
File file2 =new File(myDir,"new2.txt");
try {
file1.createNewFile();
file2.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
file1.delete();//delete()方法不需要进入异常块
File newNameError = new File("newName.txt");//默认文件夹是源程序所在文件夹
file2.renameTo(newNameError);//此方法会在程序目录下,新建一个文件,而不会rename掉原有的;rename()方法不需要进入异常块
File newNameCorrect =new File(myDir,"newName.txt");//重命名文件
file2.renameTo(newNameCorrect);
File newDirError =new File("newDir");//重命名目录
myDir.renameTo(newDirError);//注意即使目录不为空,也可以重命名.在源程序所在文件夹新建newDir并复制cy文件夹下的文件至此
File newDirCorrect =new File("D:\\newDir");
myDir.renameTo(newDirCorrect);
String[] files =new String[20];
File searchDir =new File("D:\\");//查找D盘根目录下所有文件和文件夹,因为在操作系统看来文件和文件夹是一样的
files =searchDir.list();//可以找到隐藏文件夹
for(String fn : files){
System.out.println("found:"+fn);
}
//outPut is:
// found:$RECYCLE.BIN
// found:CER_Backup
// found:comtypes
// found:cy
// found:j2ee_lib
// found:JAVA
// found:masm5
// found:MySQL Datafiles
// found:newDir
// found:Program Files
// found:Programming
// found:RECYCLER
// found:SQL2KSP4
// found:System Volume Information
// found:test.txt
// found:VC98
// found:学校事宜
// found:手机证书备份
}
//-------FileWriter和FileReader类的使用--------
public void fileWriterAndReader(){
char[] in =new char[50];//大小为50的话,最后null的数据,会用□代替
int size =0;
File file =new File("fileWriter.txt");//从内存读出到文件中
try {
FileWriter fw =new FileWriter(file);//创建空文件,原有同名文件会被删除
fw.write("how\nare\nyou!\n");
fw.flush();//从内存像外写出时,由于开始的内容是在内存中,此例为"how are you"。你不知道何时内存(流)何时会把数据发送出去,所以在关闭流时,需要调用此方法,已确定内存(流)中的数据能全部发送
fw.close();
FileReader fr =new FileReader(file);//从文件读入到内存中
size =fr.read(in);//read()方法一个字符一个字符的读取整个文件,并将读取的字符放到字符数组中,注意read()方法的返回值!
System.out.println("size:"+size);
for(char c : in){
System.out.print(c);
}
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
//outPut is:
//size:13
//how
//are
//you!
}
//-------组合IO类的使用--------
public void compositIO(){
File file =new File("fileWriter2.txt");
try {
PrintWriter pw =new PrintWriter(file);//Writer和Stream会根据文件名自动创建一个新的文件,可是却不会创建一个新目录,即创建目录只有一种方式,即mkdir()
pw.println("how");pw.println("are");pw.println("you!");//自动带换行
pw.flush();pw.close();//注意刷新和关闭流
FileReader fr =new FileReader(file);
BufferedReader bfr =new BufferedReader(fr);
String data =bfr.readLine();//只读取了一行,当没有数据时会返回null,所以null是停止读取文件的信号
System.out.println(data);
while((data =bfr.readLine()) !=null){//从 "are"开始读而不是"how",所以在未关闭一个流并重启一个新流时 readLine()是游标记录的
System.out.println(data);
}
//fr.close();
bfr.close();//注意刷新和没必要关闭两个流,在关闭了bfr之后,就相当于同时关闭了fr,有人建议让bfr=null。
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//outPut is:
//how
//are
//you!
}
//-------Console类的使用--------
public void consoleForUse(){
Console c =System.console();//单例模式,唯一的Console对象,所以不能用new
char[] pwc =new char[10];//??
pwc =c.readPassword("%s","pw: ");//输出pw: 键盘输入才作为readPassword()的返回值
for(char ch: pwc){
c.format("%c", ch);
}
c.format("\n");
while(true){
String name =c.readLine("%s","input?: ");
c.format("outPut is: %s\n", name);
}
/*虚拟机是否有一个控制台Console取决于所依赖的平台和虚拟机解析该方法的方式。如果虚拟机是从一个交互式的命令行中启动的,而没有重定向标准输入和输出流,那么虚拟机会自动的连接到键盘作为标准输入,并且把启动虚拟机的地方作为标准输出。如果虚拟机是自动启动的,例如通过后台的一个任务计划,那么典型的情况就是没有Console控制台……。
于是,思考一下我们运行上面程序的地点——Eclipse等集成开发环境,这对于上面描述中的把启动虚拟机的地方作为标准输出来说是不合适的,这里的Console()返回的默认情况下是Null,于是就产生了上面的出错信息。(也许未来Eclipse会有所改进吧)
怎么解决该问题呢?这里提供两条思路给大家(已经实际操作过,可以实现功能的正常运作)
1、使用命令行进行运行,编译可以使用集成开发环境。这样可以完成标准输出。
!//我认为编译也不能使用集成开发环境,因为有包和目录的影响,直接将.java文件拷到一个地方,用jdk编译就好了。
2、在程序中重定向标准输出到其他的设备或者方式(例如写到文本文件),这样也可以“比较不方便的”完成该功能。
*/
}
public static void main(String[] args){
IOClass ioc =new IOClass();
//ioc.createForFile();
//ioc.createForDirectory();
//ioc.delAndRenameAndFind();
//ioc.fileWriterAndReader();
//ioc.compositIO();
//ioc.consoleForUse();
}
/*
* 不关闭I/O流的坏处:
* 1.不关闭文件会浪费系统资源,与数据库连接资源类似。程序每执行一段代码都占用一部分内存,如果不关闭的话肯定会浪费内存的,而且如果有动态分配的内存,那还会造成内存泄露。
2.每个系统打开文件数量是有一限制的,如果打开文件不关闭,当连接数满的时候就无法再打开文件了。一般一个操作系统能最多打开1024个文件,但这个不一定,与机器硬件配置和系统配置有关。老点的机器只能同时打开256个或更低。
3.IO流也有独占模式,也就是锁的概念,打开一个文件流以后,如果是以读的模式打开那就是共享锁,其它程序也可访问读取;如果以写的模式打开一般为独占,其它程序不能访问.具体表现情况还要看操作系统或者应用程序是如何处理的,因为底层的程序和高层的程序不一样。
* */
}
分享到:
相关推荐
Chapter 6 - Server-side Scheduling in Cluster Parallel I/O Systems Chapter 7 - Design and Implementation of a Large Virtual NVRAM Cache for Software RAID Part Three - Appendices Appendix 1 - ...
Chapter 2 I/O Streams as an introduction to Objects and Classes
chapter 11 初级I/O函数 chapter 12 标准I/O函数 chapter 13 进程及流程控制 chapter 14 格式化输入输出函数 chapter 15 文件及目录函数 chapter 16 信号函数 chapter 17 错误处理函数 chapter 18 管道相关函数 ...
This chapter completes the I/O troika with a treatment on advanced I/O interfaces, memory mappings, and optimization techniques. The chapter is capped with a discussion on avoiding seeks and the role ...
This chapter completes the I/O troika with a treatment on advanced I/O interfaces, memory mappings, and optimization techniques. The chapter is capped with a discussion on avoiding seeks, and the role...
Chapter 8 - I/O Flow and Dispatching Chapter 9 - I/O Targets Chapter 10 - Synchronization Chapter 11 - Driver Tracing and Diagnosability Chapter 12 - WDF Support Objects Chapter 13 - UMDF ...
NULL 博文链接:https://hnzhoujunmei.iteye.com/blog/768806
Chapter 1 presents a broad overview of I/O in terms of Java’s classic I/O, New I/O (NIO), and NIO.2 categories. You learn what each category offers in terms of its capabilities, and you also learn ...
Chapter 4: File I/O: The Universal I/O Model Chapter 5: File I/O: Further Details Chapter 6: Processes Chapter 7: Memory Allocation Chapter 8: Users and Groups Chapter 9: Process Credentials Chapter...
Chapter 12 I/O project: Building a Command Line Program Separation of Concerns for Binary Projects 将代码程序分为main.rs和lib.rs,将程序的逻辑logic移动到lib.rs 当parsing逻辑足够小时可以放在main.rs下 ...
Chapter 10 FILE I/O 577 Chapter 11 RECURSION 647 Chapter 12 UML AND PATTERNS 689 Chapter 13 INTERFACES AND INNER CLASSES 711 Chapter 14 GENERICS AND THE ArrayList CLASS 759 Chapter 15 LINKED DATA ...
PDF和EPUB两个格式文件 What You'll Learn Build modularized applications in Java ...Chapter 12: I/O Chapter 13: Security Chapter 14: User Interface Chapter 15: JVM Chapter 16: Miscellaneous
Chapter 6: Strings, I/O, Formatting, and Parsing
Java语言程序设计基础篇课后题答案-Chapter18BinaryI_O.pdf
chapter 6 File I/O and Serialization chapter 7 Controls chapter 8 Dialog Boxes and Property Sheets Part II The Document/View Architecture chapter 9 Documents,Views,and the Single Document ...
Chapter 6. Processes, Threads, and Jobs Process Internals Flow of CreateProcess Thread Internals Examining Thread Activity Thread Scheduling Job Objects Conclusion Chapter 7. Memory ...
CHAPTER 2 Using the Windows File System and Character I/O 25 CHAPTER 3 Advanced File and Directory Processing, and the Registry 59 CHAPTER 4 Exception Handling 101 CHAPTER 5 Memory Management, Memory-...