-4

am new to java programming I need a program to read a certain information from a file and select the particular informationwhich is needed and then write this particular information into a text file .

{

 BufferedReader in = new BufferedReader (newFileReader("C:/Users/ngorentl/"));
    String info = "";
    String info1 = "";
    int startLine = 111 ;
    int endLine = 203 ;
    int sl = 221;
    int el =325;

// reading only the specific info which is needed and that is printing in the console

   for (int i = 0; i < startLine; i++) { info = in.readLine(); }
    for (int i = startLine; i < endLine + 1; i++) {
        info = in.readLine();
        System.out.println(info);
    }
       for (int j = 203; j < sl; j++) { info1 = in.readLine(); }
        for (int j = sl; j < el + 1; j++) {
            info1 = in.readLine();
           System.out.println(info1);
        }

     // having a problem from here i dont know whether this is the correct approach 
        File fin = new File(info); // getting an error here
        FileInputStream fis = new FileInputStream(fin);
        BufferedReader is = new BufferedReader(new InputStreamReader(fis));     
        FileOutputStream fos = new FileOutputStream("hh.txt");
        OutputStreamWriter osw= new OutputStreamWriter(fos);
        BufferedWriter bw = new BufferedWriter(osw);
        String aLine = null;
        while ((aLine = is.readLine()) != null) {
        bw.write(aLine);
        bw.newLine();
        bw.flush();
        bw.close();
        is.close();
        }
        in.close();

}

1 Answers1

0

File fin = new File(String fileName) is the correct syntax. eg. File fin = new File("C:\abc.txt");

[UPDATE] Assuming your question is about writing a String to file. In Java 7

try(  PrintWriter out = new PrintWriter( "filename.txt" )  ){
out.println( info); 
}

In Java 6 or below, use

try {
        BufferedWriter out = new BufferedWriter(new FileWriter("sample.txt"));
        out.write(info);
        out.close();
    }
    catch (IOException e)
    {
        System.out.println("Exception ");       
    }

and possible correction of your code, so variable info has all that information

for (int i = startLine; i < endLine + 1; i++) {
    info    +=   in.readLine();
}

    System.out.println(info);
Anurag Awasthi
  • 238
  • 2
  • 13