java程序怎样读取linux系统下的文件

2024-11-18 09:19:05
推荐回答(1个)
回答1:

import java.io.*;

public class FileToString {
     public static String readFile(String fileName) {
        String output = ""; 
        
        File file = new File(fileName);
           
        if(file.exists()){
            if(file.isFile()){
                try{
                    BufferedReader input = new BufferedReader (new FileReader(file));
                    StringBuffer buffer = new StringBuffer();
                    String text;
                       
                    while((text = input.readLine()) != null)
                        buffer.append(text +"/n");
                       
                    output = buffer.toString();                    
                }
                catch(IOException ioException){
                    System.err.println("File Error!");

                }
            }
            else if(file.isDirectory()){
                String[] dir = file.list();
                output += "Directory contents:/n";
                
                for(int i=0; i                    output += dir[i] +"/n";
                }
            }
        }
        else{
            System.err.println("Does not exist!");
        }
        return output;
     }
     
     public static void main (String args[]){
         String  str = readFile("/home/1.txt");
         
         System.out.print(str);
     }
}