【问题标题】:Edit Linux Network Configuration File("/etc/network/interfaces") through code通过代码编辑 Linux 网络配置文件(“/etc/network/interfaces”)
【发布时间】:2017-06-02 16:38:10
【问题描述】:

我想在 App 中添加一个功能,用户可以永久更改机器 IP 方案(IP、SubnetMask、DefaultGateway),所以我想对 Linux 网络配置文件(“/etc/network”)进行读/写操作/interfaces") 使用以下代码。

 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();

问题是对 while() 循环的检查一直返回 false。 我对任何替代方法进行了一些研究,包括使用 BufferedReader 或 Scanner 来读取文件,但没有奏效。以下所有检查一直返回 false。

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

虽然文件确实存在,但它包含它的内容但是每次我尝试使用上面的代码读取它时,所有文件内容都会被删除并且文件变空。

我错过了什么吗?有没有更好的选择?我还尝试读取同一目录中的另一个文件,该文件对所有用户具有读/写/执行的完全权限,但结果仍然相同

【问题讨论】:

  • 我认为这是因为您没有正确的管理员权限来打开此文件。也许是一个好的开始阅读:stackoverflow.com/questions/36828036/…
  • 你应该重新考虑你的解决方案
  • 我已经尝试过直接通过代码运行命令来更改 Ip/Subnet (sudo ifconfig eth0 new_ip netmask new_subet),这可以解决问题并永久执行。但不幸的是,DefaultGateway 不是(sudo route add default gw new_gw)。当机器重新启动时,它会从“接口”文件中加载它。使用脚本不是我的选择。那么您认为我应该采取的任何其他解决方案吗?感谢。谢谢

标签: java linux file networking


【解决方案1】:

当我试图打开要写入和读取的文件时,导致问题和循环在开始时终止。所以事实证明,对于同一个文件,您不应该在 FileReader 之前使用 FileWriter。同时这样做会导致文件阅读器读取空文件并终止循环,因为它在开始时就获得了 EndOfFile。之后它将文件关闭为空,因此其所有内容都将丢失。

更好的方法是

  • 首先以“只读”方式打开文件。
  • 逐行扫描文件并保留每行解析的缓冲区(在我的情况下为列表)。
  • 当您到达标记行时,在文件中添加您希望更新的内容并更新您的缓冲区。
  • 现在打开文件“写”你更新的列表就可以了

注意:这适用于文件大小相当小以适应文件处理时间的情况。

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();
}

现在分开写。而且您还想重新启动网络服务

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");

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-06
    • 2013-11-06
    • 1970-01-01
    • 1970-01-01
    • 2015-05-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-11
    相关资源
    最近更新 更多