File.pathSeparator指的是分隔连续多个路径字符串的分隔符,例如:
java -cp test.jar;abc.jar HelloWorld
就是指“;”
File.separator才是用来分隔同一个路径字符串中的目录的,例如:
C:\Program Files\Common Files
就是指“\”
表示目录的分隔符连续多个路径字符串的分隔符
window “\” ;
Linux “/” :
如果要跨平台在写目录分隔符时应写 File.separator
IO操作都会有一定的延迟,因为依靠JVM来完成
File f = new File("d:\\test.txt") ;
f.createNewFile() ;
删除文件时判断文件是否存在
public class FileDemo06 {
public static void main(String args[]) throws Exception {
File f = new File("d:" + File.separator + "test.txt"); // 实例化File类的对象
if (f.exists()) { // 如果文件存在则删除
f.delete(); // 删除文件
} else {
f.createNewFile(); // 创建文件,根据给定的路径创建
}
}
};
创建文件夹 mkdir()
列出指定目录的全部文件
public class FileDemo08{
public static void main(String args[]){
File f = new File("d:"+File.separator) ; // 实例化File类的对象
String str[] = f.list() ; // 列出给定目录中的内容
for(int i=0;i<str.length;i++){
System.out.println(str[i]) ;
}
}
};
判断是否是目录
isDirectory()
列出指定目录的全部内容,如果有子文件夹也列出子文件夹的内容,递归实现
public class IODemo {
public static void main(String[] args) {
File f = new File("d:" + File.separator);
listFile(f);
}
public static void listFile(File f) {
if (f != null) {
if (f.isDirectory()) {
File[] files= f.listFiles();
if(files != null){ // 文件夹为空
for (File file : files) {
listFile(file);
}
}
} else {
System.out.println(f);
}
}
}
}
向文件中写入字符串
public class IODemo{
public static void main(String args[]) throws Exception {
File f = new File("d:" + File.separator + "test.txt");
FileOutputStream fos = new FileOutputStream(f);
byte[] bytes = "hello world".getBytes();
//fos.write(bytes);
for (byte b : bytes) { //一个个字节写入
fos.write(b);
}
fos.close();
}
};
如果不想覆盖以前的内容,则可以追加新内容 换行 \r\n
public class IODemo{
public static void main(String args[]) throws Exception {
File f = new File("d:" + File.separator + "test.txt");
FileOutputStream fos = new FileOutputStream(f,true);
fos.write("\r\ni am programmer".getBytes());
fos.close();
}
};
从文件中读取内容
public class IODemo{
public static void main(String args[]) throws Exception {
File f = new File("d:" + File.separator + "test.txt");
FileInputStream fis = new FileInputStream(f);
// byte[] b = new byte[1024];
// fis.read(b);
// System.out.println(new String(b));//后面有大量空格 不合适
byte[] b = new byte[1024];
int len = fis.read(b);
System.out.println(new String(b,0,len));
}
};
上面虽然最后指定了数组的范围,但程序依然开辟了很多无用空间,f.lenth()改进
public class IODemo{
public static void main(String args[]) throws Exception {
File f = new File("d:" + File.separator + "test.txt");
FileInputStream fis = new FileInputStream(f);
byte[] b = new byte[(int) f.length()];
fis.read(b);
System.out.println(new String(b));
}
};
也可以循环一个个读取
public class IODemo{
public static void main(String args[]) throws Exception {
File f = new File("d:" + File.separator + "test.txt");
FileInputStream fis = new FileInputStream(f);
byte[] b = new byte[(int) f.length()];
for (int i = 0; i < b.length; i++) {
b[i] = (byte) fis.read();
}
System.out.println(new String(b));
}
};
如果不知道输入的内容有多大,通过判断是否读到文件末尾
public class IODemo {
public static void main(String args[]) throws Exception {
File f = new File("d:" + File.separator + "test.txt");
FileInputStream fis = new FileInputStream(f);
byte[] b = new byte[1024];
int len = 0;
int temp = 0;
while((temp = fis.read())!=-1){
b[len] = (byte) temp;
len ++;
}
System.out.println(new String(b));
}
};
字符流
writer
一个字符等于2个字节
public class IODemo {
public static void main(String args[]) throws Exception {
File f = new File("d:" + File.separator + "test.txt");
Writer fw = new FileWriter(f);
fw.write("hello world");
fw.close();
}
};
追加文件内容
public class IODemo {
public static void main(String args[]) throws Exception {
File f = new File("d:" + File.separator + "test.txt");
Writer fw = new FileWriter(f,true);
fw.write("\r\n i am programmer");
fw.close();
}
};
Reader
public class IODemo {
public static void main(String args[]) throws Exception {
File f = new File("d:" + File.separator + "test.txt");
FileReader fr = new FileReader(f);
char c[] = new char[1024];
int len = fr.read(c);
fr.close();
System.out.println(new String(c,0,len));
}
};
使用循环读取
public class IODemo {
public static void main(String args[]) throws Exception {
File f = new File("d:" + File.separator + "test.txt");
FileReader reader = new FileReader(f);
char c[] = new char[1024];
int temp = 0;
int len = 0;
while((temp=reader.read())!=-1){
c[len] = (char) temp;
len++;
}
reader.close();
System.out.println(new String(c,0,len));
}
};
字符流和字节流的区别
字符流将数据先放入缓存后,在写入文件
字节流直接操作文件
当字符流和字节流写文件时都不关闭流,发现使用字节流,文件中有内容,而字符流没有内容。因为关闭流,强制将缓冲区的内容进行输出
flush():强制清空缓冲区内容
缓冲区:可以理解为一段特殊的内容,当程序频繁需要读取数据时,将数据暂存在缓冲区中,从缓冲区里读取速度比较快。
文件的复制
使用字节流,因为文件有可能是图片视频
边读边写
public class Copy{
public static void main(String args[]) {
if(args.length != 2){
System.out.println("输入的参数不正确!");
System.out.println("java Copy 源文件路径,目标文件路径");
System.exit(1);
}
File f1 = new File(args[0]);
File f2 = new File(args[1]);
System.out.println(f1.getAbsolutePath());
if(!f1.exists()){
System.out.println("源文件不存在");
System.exit(1);
}
try {
InputStream is = new FileInputStream(f1);
OutputStream os = new FileOutputStream(f2);
int temp = 0;
while((temp =is.read())!=-1){
os.write(temp);
}
System.out.println("复制完成!");
} catch (Exception e) {
e.printStackTrace();
}
}
};
转换流
OutputStreamWriter
将输出的字符流变为字节流
public class IODemo {
public static void main(String args[]) throws Exception {
File f = new File("d:" + File.separator + "test.txt");
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(f));
out.write("hello world");
out.close();
}
};
InputStreamReader
将输入的字节流变为字符流
public class IODemo {
public static void main(String args[]) throws Exception {
File f = new File("d:" + File.separator + "test.txt");
InputStreamReader in = new InputStreamReader(new FileInputStream(f));
char[] c = new char[1024];
int len = in.read(c);
System.out.println(new String(c,0,len));
}
};
最终都是以字节的形式保存在文件中
内存操作流
ByteArrayInputStream
把数据写入到内存中
ByteArrayOutputStream
从内存中读取数据
public class IODemo {
public static void main(String args[]) throws Exception {
String str = "HELLO WORLD";
ByteArrayInputStream bis = new ByteArrayInputStream(str.getBytes());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int temp = 0;
while((temp=bis.read())!=-1){
bos.write(Character.toLowerCase(temp));
}
System.out.println(bos.toString());
bis.close();
bos.close();
}
};
打印流
public class IODemo {
public static void main(String args[]) throws Exception {
PrintStream ps = null; // 声明打印流对象
// 如果现在是使用FileOuputStream实例化,意味着所有的输出是向文件之中
ps = new PrintStream(new FileOutputStream(new File("d:"
+ File.separator + "test.txt")));
ps.print("hello ");
ps.println("world!!!");
ps.print("1 + 1 = " + 2);
ps.close();
}
};
打印流进行格式化
public class IODemo {
public static void main(String args[]) throws Exception {
PrintStream ps = new PrintStream(new FileOutputStream(new File("d:"
+ File.separator + "test.txt")));
String name = "zqt";
int age = 25;
float score = 990.356f;
char sex = 'M';
ps.printf("姓名:%s;年龄:%d;成绩:%f;性别:%c", name, age, score, sex);
ps.close();
}
};
System.in
public class IODemo {
public static void main(String args[]) throws Exception {
InputStream input = System.in; // 从键盘接收数据
byte b[] = new byte[5]; // 开辟空间,接收数据
System.out.print("请输入内容:"); // 提示信息
int len = input.read(b); // 接收数据
System.out.println("输入的内容为:" + new String(b, 0, len));
input.close(); // 关闭输入流
}
};
1.如果输入的数据超过了范围,则只能驶入部分数据
2.如果指定byte数组长度为奇数,会出现乱码
public class IODemo {
public static void main(String args[]) throws Exception {
InputStream input = System.in; // 从键盘接收数据
StringBuffer buf = new StringBuffer(); // 使用StringBuffer接收数据
System.out.print("请输入内容:"); // 提示信息
int temp = 0; // 接收内容
while ((temp = input.read()) != -1) {
char c = (char) temp; // 将数据变为字符
if (c == '\n') { // 退出循环,发生的房间放多少输入回车表示输入完成
break;
}
buf.append(c); // 保存内容
}
System.out.println("输入的内容为:" + buf);
input.close(); // 关闭输入流
}
};
一个汉字是分两次读取的,输入中文,仍然会产生乱码
可以将数据暂放到一块内存中,然后一次性从内存中读取数据
BufferedReader
从缓冲区读取内容,构造方法只能接受字符输入流的实例
修改上面的程序
public class IODemo {
public static void main(String args[]) throws Exception {
BufferedReader buf = new BufferedReader(new InputStreamReader(System.in)) ; // 将字节流变为字符流
String str = null ; // 接收输入内容
System.out.print("请输入内容:") ;
try{
str = buf.readLine() ; // 读取一行数据
}catch(IOException e){
e.printStackTrace() ; // 输出信息
}
System.out.println("输入的内容为:" + str) ;
}
};
输入输出重定向
将System.in 设置成从文件中读取
public class IODemo {
public static void main(String args[]) throws Exception {
System.setIn(new FileInputStream("d:" + File.separator + "test.txt")); // 设置输入重定向
InputStream input = System.in; // 从文件中接收数据
byte b[] = new byte[1024];// 开辟空间,接收数据
int len = input.read(b); // 接收
System.out.println("输入的内容为:" + new String(b, 0, len));
input.close(); // 关闭输入流
}
};
将System.out设置成输出到文件
public class IODemo {
public static void main(String args[]) throws Exception {
System.setOut(new PrintStream(new FileOutputStream("d:" + File.separator + "test.txt"))); // 设置输入重定向
System.out.print("www.csdn.com"); // 输出时,不再向屏幕上输出
System.out.println("\r\nzqt");
}
};
对输入数据进行检测
public class InputData{
private BufferedReader buf = null ;
public InputData(){// 只要输入数据就要使用此语句
this.buf = new BufferedReader(new InputStreamReader(System.in)) ;
}
public String getString(String info){ // 得到字符串信息
String temp = null ;
System.out.print(info) ; // 打印提示信息
try{
temp = this.buf.readLine() ; // 接收数据
}catch(IOException e){
e.printStackTrace() ;
}
return temp ;
}
public int getInt(String info,String err){ // 得到一个整数的输入数据
int temp = 0 ;
String str = null ;
boolean flag = true ; // 定义一个标记位
while(flag){
str = this.getString(info) ; // 接收数据
if(str.matches("^\\d+$")){ // 判断是否由数字组成
temp = Integer.parseInt(str) ; // 转型
flag = false ; // 结束循环
}else{
System.out.println(err) ; // 打印错误信息
}
}
return temp ;
}
public float getFloat(String info,String err){ // 得到一个小数的输入数据
float temp = 0 ;
String str = null ;
boolean flag = true ; // 定义一个标记位
while(flag){
str = this.getString(info) ; // 接收数据
if(str.matches("^\\d+.?\\d+$")){ // 判断是否由数字组成
temp = Float.parseFloat(str) ; // 转型
flag = false ; // 结束循环
}else{
System.out.println(err) ; // 打印错误信息
}
}
return temp ;
}
public Date getDate(String info,String err){ // 得到一个小数的输入数据
Date temp = null ;
String str = null ;
boolean flag = true ; // 定义一个标记位
while(flag){
str = this.getString(info) ; // 接收数据
if(str.matches("^\\d{4}-\\d{2}-\\d{2}$")){ // 判断是否由数字组成
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd") ;
try{
temp = sdf.parse(str) ; // 将字符串变为Date型数据
}catch(Exception e){}
flag = false ; // 结束循环
}else{
System.out.println(err) ; // 打印错误信息
}
}
return temp ;
}
};
Scanner
Scanner scan = new Scanner(System.in) ; // 从键盘接收数据
System.out.print("输入数据:") ;
String str = scan.next() ; // 接收数据
System.out.println("输入的数据为:" + str) ;
如果输入的数据Hello world 中间带有空格,则只能输出Hello 因为scanner将空格作为分隔符
Scanner scan = new Scanner(System.in) ; // 从键盘接收数据
System.out.print("输入数据:") ;
scan.useDelimiter("\n") ;
String str = scan.next() ; // 接收数据
System.out.println("输入的数据为:" + str) ;
输入int.float 数据,之前先验证一下
Scanner scan = new Scanner(System.in) ; // 从键盘接收数据
int i = 0 ;
float f = 0.0f ;
System.out.print("输入整数:") ;
if(scan.hasNextInt()){ // 判断输入的是否是整数
i = scan.nextInt() ; // 接收整数
System.out.println("整数数据:" + i) ;
}else{
System.out.println("输入的不是整数!") ;
}
System.out.print("输入小数:") ;
if(scan.hasNextFloat()){ // 判断输入的是否是小数
f = scan.nextFloat() ; // 接收小数
System.out.println("小数数据:" + f) ;
}else{
System.out.println("输入的不是小数!") ;
}
日期格式的输入
Scanner scan = new Scanner(System.in) ; // 从键盘接收数据
String str = null ;
Date date = null ;
System.out.print("输入日期(yyyy-MM-dd):") ;
if(scan.hasNext("^\\d{4}-\\d{2}-\\d{2}$")){ // 判断
str = scan.next("^\\d{4}-\\d{2}-\\d{2}$") ; // 接收
try{
date = new SimpleDateFormat("yyyy-MM-dd").parse(str) ;
}catch(Exception e){}
}else{
System.out.println("输入的日期格式错误!") ;
}
System.out.println(date) ;
从文件中得到数据
File f = new File("D:" + File.separator + "test.txt") ; // 指定操作文件
Scanner scan = new Scanner(f) ; // 从键盘接收数据
StringBuffer str = new StringBuffer() ;
scan.useDelimiter("\n");
while(scan.hasNext()){
str.append(scan.next()).append('\n') ; // 取数据
}
System.out.println("文件内容为:" + str) ;