简体   繁体   中英

Edit Linux Network Configuration File(“/etc/network/interfaces”) through code

I want to add a functionality in the App where the user can change machine IP scheme (IP, SubnetMask, DefaultGateway) permanently, So I want to do Read/Write operation on the Linux Network Configuration File ("/etc/network/interfaces") using following code.

 File file = new File("/etc/network/interfaces");
 boolean exists = file.exists();
 String line = "";

 FileWriter fw = new FileWriter(file.getAbsoluteFile());
 BufferedWriter bw = new BufferedWriter(fw);

 try
 {
    FileReader fr = new FileReader(file.getAbsoluteFile());
    //BufferedReader br = new BufferedReader(fr); 
    Scanner scan = new Scanner(new FileInputStream(file));

    if(exists)
    {
        while(scan.hasNext())     //while((line = br.readLine()) != null)
        {
            // Any Write operation                  
        }
        scan.close();             // br.close
    }
 }
bw.close();

Problem is that the check on while() loop keeps returning false. I did some research for any alternative for that which includes using BufferedReader or Scanner to read the file but didn't work. All the following checks just keep returning false.

while(scan.hasNext())
while(scan.hasNextLine())
while((line = br.readLine()) != null)

Although file does exist, it contains its content But every time I try to read it with the above code all file content gets removed and the file gets empty.

Am I missing something? Is there any better alternative? I've also tried reading another file in the same directory which has full permission of read/write/execute for all users but still same result

As I'm trying to open the file to write and read was what causing the issue and loop gets terminated in the beginning. So it turns out that You should not use FileWriter before FileReader for same file. Doing so at the same time causing File reader to read empty file and loop terminates as it gets EndOfFile right at the beginning. Afterwards it closes the file empty hence all its contents are being lost.

Better way was to

  • First open the file for 'Read' only.
  • Scan through file line by line & keep a buffer of each line parsed (List in my case).
  • Add the content you wish to update in the file when you get to your Marker line & update you buffer as well.
  • Now open the file to 'Write' you updated list on it

Note: This is suitable if the file size is reasonably small to accommodate the file processing time.

File file = new File("/etc/network/interfaces");
boolean exists = file.exists();
Scanner scanner = null;
PrintWriter wirtter = null;
String line = "";
List<String> fileLines = new ArrayList<String>();

if(exists)
{
try {
    scanner = new Scanner(new FileInputStream(file));

    while(scanner.hasNextLine())
    {
        line = scanner.nextLine();
        fileLines.add(line);
        if(line.trim().startsWith("iface eth0 inet static"))
        {
            while(scanner.hasNextLine())
            {
                line = scanner.nextLine();
                fileLines.add(line);

                if(line.trim().startsWith("address"))
                {
                    String updateStr = "\taddress "+ipAddress+"\t";
                    fileLines.remove(fileLines.size()-1);
                    fileLines.add(updateStr);
                    System.out.println("IP add updated");
                }
                else if(line.trim().startsWith("netmask"))
                {
                    String updateStr = "\tnetmask "+subnetMask+"\t";
                    fileLines.remove(fileLines.size()-1);
                    fileLines.add(updateStr);
                    System.out.println("subnet add updated");
                }
                else if(line.trim().startsWith("gateway"))
                {
                    String updateStr = "\tgateway "+defaultGateway+"\t";
                    fileLines.remove(fileLines.size()-1);
                    fileLines.add(updateStr);
                    System.out.println("Gatway add updated");
                }

            }
        }   
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
}
finally{
    if(scanner != null)
        scanner.close();
}

Now do the Writing Separately. And Also you'd want to restart the networking service

try {
     wirtter = new PrintWriter(file);
     for (String lineW : fileLines) 
        wirtter.println(lineW);
} catch (FileNotFoundException e) {
    e.printStackTrace();
}
finally{
    if(wirtter != null)
        wirtter.close();
}
}

synchronized (p) {
    String cmd = "sudo /etc/init.d/networking restart ";
    p.exec(cmd);
    p.wait(10000);
    System.out.println("finishing restart 'Networking:' service");

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM