java根据路径读取文件

Python011

java根据路径读取文件,第1张

其读取方法为:

import java.io.File  

import java.io.FileNotFoundException  

import java.io.IOException  

import java.util.ArrayList  

  

  

public class readFile {  

    private static ArrayList<String> listname = new ArrayList<String>()  

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

        readAllFile("C:/Users/HP/Desktop")  

        System.out.println(listname.size())  

    }  

    public static void readAllFile(String filepath) {  

        File file= new File(filepath)  

        if(!file.isDirectory()){  

            listname.add(file.getName())  

        }else if(file.isDirectory()){  

            System.out.println("文件")  

            String[] filelist=file.list()  

            for(int i = 0i<filelist.lengthi++){  

                File readfile = new File(filepath)  

                if (!readfile.isDirectory()) {  

                    listname.add(readfile.getName())  

                } else if (readfile.isDirectory()) {  

                    readAllFile(filepath + "\\" + filelist[i])//递归  

                }  

            }  

        }  

        for(int i = 0i<listname.size()i++){  

            System.out.println(listname.get(i))  

        }  

    }  

}

package file.system.demo.exception

import java.io.File

import java.io.FileNotFoundException

import java.util.Scanner

public class ReadFile {

public  static String  getFile(String realpath) {

Scanner scanner = null

String text = ""

try {    

        File file= new File(realpath)

scanner = new Scanner(file)

} catch (FileNotFoundException e) {

e.printStackTrace()

}

if(scanner!=null){

while(scanner.hasNextLine()){

text+=scanner.nextLine()

}

scanner.close()

}

//System.out.println(text)

return text

}

static class InnerTest{

public static void main(String[] args) {

String realpath = "D:\\test.txt"

String text=getFile(realpath)

System.out.println(text)

}

}

}

实现方式有很多,还可以用字节流FileInputStream,字符流FileReader等方式读取