如何使用Java IO功能更改文件的价值如何使用、价值、功能、文件

2023-09-07 00:21:00 作者:裤兜揣着棒棒糖

谁能帮助我如何使用Java IO功能改变行的文件。该文件位于 SD卡的。我试图从不同的博客有些解决方案,但未能成功。

我需要改变一个属性 wpa_oper_channel = 1 2,3,4 ..... 作为在该文件中的用户需求 SD卡/ sample.txt的

我也用 SED 命令试过了,但仍然没有工作。请建议,如果有使用Java IO功能的任何解决方案。

该命令我一直在使用使用 SED

  SED -i的/ wpa_oper_channel = [0-9] \\\\ + / wpa_oper_channel = 7 /'为sample.txt 

解决方案

如果您的配置文件是一个属性文件的形式。这意味着每行是的key = value 的格式。您可以轻松地读取,修改和写。下面是一个例子,我假设你有读书并没有什么问题,通过流写入文件。

 文件SD卡= Environment.getExternalStorageDirectory();档案文件=新的文件(SD卡,sample.txt的);InputStream为=新的FileInputStream(文件); //读取现有的文件属性道具=新特性();props.load(是);props.setProperty(wpa_oper_channel,4);出的OutputStream =新的FileOutputStream(文件); //你的输出文件流prop.store(输出,NULL); //保存您的属性文件没有头 
Java IO,硬骨头也能变软

通过这样做,你可能,如果有这样的评语线的另一种类型,否则吃亏。

更新

我更新源$ C ​​$ C。但你仍然需要得到相应的读写权限。

 <使用许可权的android:NAME =android.permission.WRITE_EXTERNAL_STORAG​​E/> 

我没有测试code,它会与一些异常处理工作。如果它不能正常工作,请注明您的错误。

Can anyone help me how to change a line in a file using java IO function. The file is located at SDCard. I have tried some solution from different blog, but failed.

I need to change one attribute wpa_oper_channel=1 to 2,3,4..... as user demand in the file sdcard/sample.txt.

I have also tried using SED command, but still not working. Please suggest if there any solution using java IO function.

The Command I have used using SED :

sed -i 's/wpa_oper_channel=[0-9]\\+/wpa_oper_channel=7/' sample.txt

解决方案

If your configuration file is in the form of a Properties file. This means each line is in a format of key=value. You can easily read, modify and write it. Here is an example, I assume you have no problem with reading and writing a file through streams.

File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard,"sample.txt");
InputStream is = new FileInputStream(file); // Read your existing file
Properties props = new Properties();
props.load(is);
props.setProperty("wpa_oper_channel", "4");
OutputStream out = new FileOutputStream(file); // Your output file stream
prop.store(output, null); // Save your properties file without header

By doing this, you may lose if there is another type of line like comments or else.

Update

I updated to source code. But still you need to get read and write permission.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

I haven't test the code, It will work with some exception handling. If it is not work please specify your error.