package Demo;
import java.io.*;
public class JavaIO {
public static void main(String[] args){
try {
//文件IO,File对象既可以表示文件,也可以表示目录
File f1 = new File("C:\Users\shun.guo\Desktop\Java\javatest\test.txt");
System.out.println(f1);
File f2 = new File("C:\Users\shun.guo\Desktop\Java\javatest");
System.out.println(f1.isDirectory());//false
System.out.println(f1.isFile());//true
System.out.println(f2.isDirectory());//true
System.out.println(f2.isFile());//false
//creat file
File creatfile1 = new File("C:\Users\shun.guo\Desktop\Java\javatest2");
File creatfile2 = new File("C:\Users\shun.guo\Desktop\Java\javatest\test2.txt");
if (!creatfile1.exists()) {
System.out.println("不存在目录,开始创建这个目录路径");
creatfile1.mkdir();//创建目录
}else{
System.out.println("目录已经存在");
}
if (!creatfile2.exists()) {
System.out.println("不存在文件,开始创建文件");
creatfile2.createNewFile();//创建文件
}else {
System.out.println("文件已经存在");
}
//listdir
File f4 = new File("C:\Users\shun.guo\Desktop\Java\javatest");
File[] f4listdir = f4.listFiles();
System.out.println("列出路径"+f4+"下的所有文件");
for (File j : f4listdir){
System.out.println(j);
}
}catch (Exception e){//IO操作的时候必须捕获异常
System.out.println("异常");
e.printStackTrace();
}
}
}
读取txt文件
package Demo;
import java.io.*;
public class readtxt {
//java read txt
public static void main(String[] args) throws IOException{
String filename="C:\Users\shun.guo\Desktop\Java\javatest\test2.txt";
FileReader reader = new FileReader(filename);
BufferedReader buffreader = new BufferedReader(reader);//使用Bufferreader封装filereader
String line = buffreader.readLine();
while (line != null){
System.out.println(line);
line=buffreader.readLine();//bufferreader读取到最后一行会返回null
}
buffreader.close();
reader.close();
}
}
package Demo;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class JavaIoInputstream {
public static void readFile(){
try{
InputStream input = new FileInputStream("D:\Uesrs\shun.guo\Desktop\Java\javatest\test2.txt");
for (;;){
int n = input.read();
if (n == -1){
break;
}
System.out.println(n);
}
input.close();
}catch (Exception e){
e.printStackTrace();
}
}
public static void main(String[] args){
JavaIoInputstream.readFile();
}
}