read file in classpath

前端 未结 3 1849
长情又很酷
长情又很酷 2020-12-07 18:12

Here is what I want to do and I am wondering if there is any Spring classes that will help with implementing. I don\'t have to use spring for this particular problem, I\'m

3条回答
  •  我在风中等你
    2020-12-07 18:53

    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;
    
    public class readFile {
        /**
         * feel free to make any modification I have have been here so I feel you
         * 
         * @param args
         * @throws InterruptedException
         */
        public static void main(String[] args) throws InterruptedException {
            File dir = new File(".");// read file from same directory as source //
            if (dir.isDirectory()) {
                File[] files = dir.listFiles();
                for (File file : files) {
                    // if you wanna read file name with txt files
                    if (file.getName().contains("txt")) {
                        System.out.println(file.getName());
                    }
    
                    // if you want to open text file and read each line then
                    if (file.getName().contains("txt")) {
                        try {
                            // FileReader reads text files in the default encoding.
                            FileReader fileReader = new FileReader(
                                    file.getAbsolutePath());
                            // Always wrap FileReader in BufferedReader.
                            BufferedReader bufferedReader = new BufferedReader(
                                    fileReader);
                            String line;
                            // get file details and get info you need.
                            while ((line = bufferedReader.readLine()) != null) {
                                System.out.println(line);
                                // here you can say...
                                // System.out.println(line.substring(0, 10)); this
                                // prints from 0 to 10 indext
                            }
                        } catch (FileNotFoundException ex) {
                            System.out.println("Unable to open file '"
                                    + file.getName() + "'");
                        } catch (IOException ex) {
                            System.out.println("Error reading file '"
                                    + file.getName() + "'");
                            // Or we could just do this:
                            ex.printStackTrace();
                        }
                    }
                }
            }
    
        }`enter code here`
    
    }
    

提交回复
热议问题