文件输入输出,可以层层遍历文件夹输出文件名
package IO;
import java.io.File;
import java.io.IOException;
public class Main1 {
public static void main(String[]args)throws IOException,ClassNotFoundException {
file();//文件对象
}
public static void file() throws IOException {
File file=new File("D:\\winpcap");
System.out.println(file.getPath()+"是否目录"+file.isDirectory());
String[]fileNameArr=file.list();
for(String fileName:fileNameArr) {
System.out.println(fileName);
}
File[]fileArr=file.listFiles();
for(File childFile:fileArr) {
System.out.println(childFile.getPath());
}
findAllFile(file);//显示所有文件和层层文件夹内容
File aFile=new File("E:/桌面的文件.rar");
if(!aFile.exists()) {
boolean create=aFile.createNewFile();
System.out.println(create);
}else {
aFile.delete();
}
System.out.println(aFile.length());
}
private static void findAllFile(File file) {
if(file.isDirectory()) {
System.out.println("目录"+file.getPath());
File[]files=file.listFiles();
for(File childFile:files) {
findAllFile(childFile);
}
}else {
System.out.println("文件"+file.getPath());
return;
}
}
}
字节输入输出,拷贝文件内容
package IO;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
public class Main1 {
public static void main(String[]args)throws IOException,ClassNotFoundException {
inputStream();//字节输入输出流
}
private static void inputStream() throws IOException {
InputStream is=null;
OutputStream os=null;
try {
File file=new File("C:\\Users\\11816\\Desktop\\专业学习\\test.txt");
is=new FileInputStream("C:\\Users\\11816\\Desktop\\专业学习\\test.txt");
//FileInputStream fis=new FileInputStream(file);
File outFile=new File("C:\\Users\\11816\\Desktop\\专业学习\\ copy.txt");
os=new FileOutputStream(outFile);
int readData=-1;
int byteCount=1;
byte[]readByte=new byte[4];
int readLen=-1;
while((readData=is.read())!=-1) {
System.out.println("读取第 " + (byteCount++) +" 字节数据 :"+readData);
os.write(readData);
}
while((readLen=is.read(readByte))>0) {
System.out.println(readLen);
System.out.println(Arrays.toString(readByte));
os.write(readByte, 0, readLen);
}
}catch(IOException e) {
throw e;
}finally {
if(is!=null) {
is.close();
}
if(os!=null) {
os.close();
}
}
}
}