我想在应用程序中添加一个功能,用户可以永久地更改机器IP方案(IP、SubnetMask、DefaultGateway),因此我想使用以下代码在("/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或扫描仪读取文件,但没有工作。以下所有检查都会一直返回false。
while(scan.hasNext())
while(scan.hasNextLine())
while((line = br.readLine()) != null)虽然文件确实存在,但它包含它的内容,但是每次我尝试用上面的代码读取它时,所有的文件内容都会被删除,文件会变得空。
我是不是遗漏了什么?还有更好的选择吗?我还尝试在同一个目录中读取另一个文件,该文件对所有用户都具有读取/写/执行的完全权限,但结果仍然相同。
发布于 2017-01-20 12:40:51
当我试图打开文件时,写和读是导致问题和循环在开始时终止的原因。因此,对于同一个文件,您不应该在FileWriter之前使用FileReader。这样做的同时,导致文件阅读器读取空文件和循环终止,因为它得到了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");
}https://stackoverflow.com/questions/41717075
复制相似问题