簡體   English   中英

通過代碼編輯Linux網絡配置文件(“ / etc / network / interfaces”)

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

我想在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)

雖然文件確實存在,但它包含其內容,但是每次我嘗試使用上述代碼讀取它時,所有文件內容都將被刪除,文件將為空。

我想念什么嗎? 還有更好的選擇嗎? 我還嘗試讀取同一目錄中的另一個文件,該文件對所有用戶具有完全讀/寫/執行權限,但結果仍然相同

當我試圖打開文件進行讀寫時,是導致問題的原因,並且循環在開始時就終止了。 因此事實證明,對於同一文件,您不應該在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");

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM