Java基础笔记总结(16)-IO流 File类练习题

2019-01-29  本文已影响0人  吵吵先生

获取文件夹的长度

private static Long getFileLength(File file) {

long len = 0;

File[] subLists = file.listFiles();

for (File subFile : subLists) {

if(subFile.isFile()){

len += subFile.length();

}else{

len +=getFileLength(subFile);

}

}

return len;

}

删除文件夹下的所有目录

public static void deleteDirectory(File file){

File[] subLists = file.listFiles();

for (File subFile : subLists) {

if(subFile.isDirectory()){

deleteDirectory(subFile);

}else if(subFile.isFile()){

  subFile.delete();

}else {

}

}

file.delete();

}

拷贝目录文件夹

public static void main(String[] args) throws IOException {

// 1、创建于目标文件相同的源文件夹

File dir = new File("ccc");

boolean flg =dir.mkdir();

copyFile(new File("aaa"), dir);

// 2、获取原文件夹中所有的文件和文件夹

// 3、遍历数组,如果是文件就用IO流读写

// 4、如果是文件夹就递归调用

}

public static void copyFile(File originFile,File destFile) throws IOException{

File[] fileList = originFile.listFiles();

for (File subFile : fileList) {

if(subFile.isDirectory()){

File subDestFile = new File(destFile.getAbsolutePath()+"\\"+subFile.getName());

subDestFile.mkdir();

copyFile(subFile, subDestFile);

}else if(subFile.isFile()){

FileInputStream fis = new FileInputStream(subFile);

FileOutputStream fos = new FileOutputStream(destFile.getAbsolutePath()+"\\"+subFile.getName());

int len = 0;

byte[] arr = new byte[1024];

while((len = fis.read(arr))!= -1){

fos.write(arr, 0, len);

}

fis.close();

fos.close();

}

}

}

按照层级打印

public static void printFileName(File file,int level){

File[] fileLists = file.listFiles();

for (File subFile : fileLists) {

for (int i = 0; i < level; i++) {

System.out.print("\t");

}

System.out.println(subFile);

if(subFile.isDirectory())

printFileName(subFile, level+1);

}

}

}

斐波拉契数列

public class Demo_Rabbit {

public static void main(String[] args) {

System.out.println(getNewRabbit(6));

}

public static int  getNewRabbit(int num){

if(num == 1){

return 1;

}else if(num ==2){

return 1;

}else{

return getNewRabbit(num-1)+getNewRabbit(num-2);

}

}

}

1000的阶乘问题

约瑟夫环

import java.util.ArrayList;

public class Demo_LuckNum {

public static void main(String[] args) {

System.out.println(getLuckNum(8));

}

public static int getLuckNum(int num){

ArrayList<Integer> list = new ArrayList<>();

for (int i = 1; i <= num; i++) {

list.add(i);

}

//去除零

int count = 1;

for (int i = 0; list.size()!=1; i++) {

if(i == list.size()){

i = 0;

}

if(count%3 == 0 ){

list.remove(i--);

}

count++;

}

return list.get(0);

}

}

上一篇下一篇

猜你喜欢

热点阅读