Wednesday, January 9, 2013

Read from a File Line by line JAVA


File:-
network devices.txt

10.30.12.106
10.30.11.155
10.60.100.97
192.168.50.197
10.60.100.96
10.10.5.75
10.10.5.100
10.10.5.76
192.168.1.1
10.10.5.68

code:-

try {
            // Open the file that is the first
            // command line parameter
            FileInputStream fstream = new FileInputStream("networkdevices.txt");
            // Get the object of DataInputStream
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine;

            int num = 0;
            //Read File Line By Line
            while ((strLine = br.readLine()) != null) {
                // Print the content on the console
                //System.out.println (strLine);
                //System.out.println ("a");

                switch (num) {
                    case 0:
                        a = strLine;
                        break;
                    case 1:
                        b = strLine;
                        break;
                    case 2:
                        c = strLine;
                        break;
                    case 3:
                        d = strLine;
                        break;
                    case 4:
                        e = strLine;
                        break;
                    case 5:
                        f = strLine;
                        break;
                    case 6:
                        g = strLine;
                        break;
                    case 7:
                        h = strLine;
                        break;
                    case 8:
                        i = strLine;
                        break;
                    case 9:
                        k = strLine;
                        break;
                    default:
                        break;
                }
                num++;
            }
            //Close the input stream
            in.close();
        } catch (Exception e) {//Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }

note:- a,b,c,d...h are strings . should be initialize globally

:)

cheers

No comments:

Post a Comment