How to change a value of a file using Java IO function

234 views Asked by At

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
3

There are 3 answers

3
bhdrkn On BEST ANSWER

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.

1
DMan On

What android do you use?

From android 4.4+ user haven't access to edit and remove files from SD Card. You must copy them to external storage and use there. See this link - http://code.google.com/p/android/issues/detail?id=67570

0
Ridcully On

You just have to

  • read the file's content into memory (there are millions of examples on how to do that with java),
  • change the content (finding the position could be done using e.g. indexOf("wpa_oper_channel="))
  • write the content back to the file (there are millions of examples for that too)