I want to know how to read a file in Java and then store the file contents into a String object...like String[] content= file contents??

here's the code of reading a file and i want the contents to be stored in a string variable...

public static void main(String[] args) throws IOException{
     File file = new File("C:/ciphertext.txt");
     int ch;
     StringBuffer strContent = new StringBuffer("");
     FileInputStream fin = null;
     String[] a = null; // I want to store the contens of file into this String a....??
     try {
      fin = new FileInputStream(file);
      while ((ch = fin.read()) != -1)
        strContent.append((char) ch);
      fin.close();
    } catch (Exception e) {
      System.out.println(e);
    }
      System.out.println(strContent.toString());

    }

plzzz help... my project is stuck!! at this point...

Recommended Answers

All 3 Replies

plz reply guys..:(

Have you tried compiling and executing your code? What was the result?

I use this method:

public String [] readFile(String filePath){
        String [] lines=new String[1000];//Enough lines.
        int counter=0;
        try{
            File file = new File(filePath);//The path of the File
            FileReader fileReader1 = new FileReader(file);
            BufferedReader buffer = new BufferedReader(fileReader1);
            boolean flag=true;
            while(true){
                try{
                    lines[counter]=buffer.readLine();//Store a line in the array.
                    if(lines[counter]==null){//If there isn't any more lines.
                        buffer.close();
                        fileReader1.close();
                        break;//Stop reading and close the readers.
                    }
                    counter++;
                }catch(Exception ex){
                    break;
                }
            }

        }catch(FileNotFoundException ex){
            System.out.println("File not found.");
        }catch(IOException ex){
            System.out.println("Exception ocurred.");
        }
        return lines;
    }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.