I have created a JSONObject and put values in it like below .
Then I converted my object "h" to string and write a file in the sdcard with that string.
JSONObject h = new JSONObject();
try {
h.put("NAme","Yasin Arefin");
h.put("Profession","Student");
} catch (JSONException e) {
e.printStackTrace();
}
String k =h.toString();
writeToFile(k);
In the file I see text written like the format below .
{"NAme":Yasin Arefin","Profession":"Student"}
My question is how do I read that particular file and convert those text back to JSONObject ?
To read a file you have 2 options :
Read with a BufferReader and your code would look like this :
//Path to sdcard
File sdcard = Environment.getExternalStorageDirectory();
//Load the file
File file = new File(sdcard,"file.json");
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
}
catch (IOException e) {
//You'll need to add proper error handling here
}
The option 2 would be to use a library such as Okio:
In your Gradle file add the library
implementation 'com.squareup.okio:okio:2.2.0'
Then in your activity:
StringBuilder text = new StringBuilder();
try (BufferedSource source = Okio.buffer(Okio.source(file))) {
for (String line; (line = source.readUtf8Line()) != null; ) {
text.append(line);
text.append('\n');
}
}
Related
I'm trying to write a function that parse a file that each line is a key = value format. The file is .txt.
Does java has a specific class or object that can help me parse the file?
note- the file has about 500K lines.
Thank you
Welcome to Stackoverflow!
You can use a BufferReader to read the file line by line:
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(
"myfile.txt"));
String line = reader.readLine();
while (line != null) {
System.out.println(line);
// read next line
line = reader.readLine();
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
And then parse the line by split over "="
String keyValue[] = line.split("=");
String key = keyValue[0];
String value = keyValue[1];
Then
So i have a .txt file in local storage its a simple text file. The text is basically just a series of lines.
I am using the code below to attempt to read the text file (i verify the file exists before calling this method).
public static String GetLocalMasterFileStream(String Operation) throws Exception {
//Get the text file
File file = new File("sdcard/CM3/advices/advice_master.txt");
if (file.canRead() == true) {System.out.println("-----Determined that file is readable");}
//Read text from file
StringBuilder text = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
System.out.println("-----" + line); //for producing test output
text.append('\n');
}
br.close();
System.out.print(text.toString());
return text.toString();
}
The code produces in the log
----Determined that file is readable
But that is the ONLY output the file data is not written to the log
Also i have tried inserting before the while loop the following to attempt to just read the first line
line = br.readLine();
System.out.println("-----" + line);
That produces the following output:
-----null
Check this out getExternalStorage
File path = Environment.getExternalStorageDirectory();
File file = new File(path, "textfile.txt");
//text file is copied in sdcard for example
Try to add a lead slash in file path /sdcard/CM3/advices/advice_master.txt
File file = new File("/sdcard/CM3/advices/advice_master.txt");
Try this. Just pass the txt file name as a parameter...
public void readFromFile(String fileName){
/*
InputStream ips;
ips = getClass().getResourceAsStream(fileName);
//reading
try{
InputStreamReader ipsr = new InputStreamReader(ips);
BufferedReader br = new BufferedReader(ipsr);
String line;
while ((line = br.readLine())!=null){
//reading goes here ;)
}
br.close();
}
catch (Exception e){
System.out.println(e.toString());
}
*/
// or try this
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard,"file.txt");
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
}
catch (IOException e) {
//You'll need to add proper error handling here
}
}
Let me refine my answer. You can try another way to read all lines from advice_master.txt and see what happens. It makes sure that all file contents can be read.
Charset charset = Charset.forName("ISO-8859-1");
try {
List<String> lines = Files.readAllLines(Paths.get(YOUR_PATH), charset);
for (String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println(e);
}
This is another question. So it seems that I have already set up the code with InputStream and Bufferstream to retrieve a String from a text file using this code:
// Read Text File entitled wordsEn.txt
public String readFromFile() {
String words = "";
try {
InputStream inputstream = openFileInput("wordsEn.txt");
if (inputstream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputstream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputstream.close();
words = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return words;
}
So what I want to do is store each string on each line of the text file into an array. I then want to be able to use this array to select a random string everytime I press a button.
Let me know.
Thanks
Colin
Just put below line into your class varialble
ArrayList<String> wordLineArray = new ArrayList<String>();
Than use add method array list to add each line of word into it.
wordLineArray.add(receiveString);
Use this line before appending it to previous buffer.
Now use this arraylist as per your requirment.
If it is helpful to you than don't forget to accept this answer.
Try using BreakIterator.getLineInstance(). Set the text to your "words" string, then iterate through each line, adding each line to a String[] array.
i am using java ant to deploy my application . I have a file app.php . I want to write some text in app.php while deploying in a specific location inside that file . This is my app.php :
'providers' => array(
'Illuminate\Validation\ValidationServiceProvider',
'Illuminate\View\ViewServiceProvider',
'Illuminate\Workbench\WorkbenchServiceProvider',
),
I want to add a line at the end of this line :
'Illuminate\Workbench\WorkbenchServiceProvider',
Please tell me how to do this .
Thanks.
you must use subString method like this:
at first store your file in a String so after that you could do this:
String s="your file";
String firstPart=s.substring(0,s.lastIndexOf(")")+1);
String lastPart=s.substring(s.lastIndexOf(")")+1);
firstPart=firstPart+"\n"+"'Illuminate\\Workbench\\WorkbenchServiceProvider',";
s=firstPart+lastPart;
How to read from file ?
Use BufferedReader to wrap a FileReader
BufferedReader br = null;
StringBuilder sb=new StringBuilder();
try {
String line;
br = new BufferedReader(new FileReader("C:\\testing.txt"));
while ((line= br.readLine()) != null) {
sb.append(line+"\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
String str=sb.toString();
See the Replace or Filter ant tasks.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to create a Java String from the contents of a file
Is it possible to process a multi-lined text file and return its contents as a string?
If this is possible, please show me how.
If you need more information, I'm playing around with I/O. I want to open a text file, process its contents, return that as a String and set the contents of a textarea to that string.
Kind of like a text editor.
Use apache-commons FileUtils's readFileToString
Check the java tutorial here -
http://download.oracle.com/javase/tutorial/essential/io/file.html
Path file = ...;
InputStream in = null;
StringBuffer cBuf = new StringBuffer();
try {
in = file.newInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
cBuf.append("\n");
cBuf.append(line);
}
} catch (IOException x) {
System.err.println(x);
} finally {
if (in != null) in.close();
}
// cBuf.toString() will contain the entire file contents
return cBuf.toString();
Something along the lines of
String result = "";
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
while (dis.available() != 0) {
// Here's where you get the lines from your file
result += dis.readLine() + "\n";
}
fis.close();
bis.close();
dis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
String data = "";
try {
BufferedReader in = new BufferedReader(new FileReader(new File("some_file.txt")));
StringBuilder string = new StringBuilder();
for (String line = ""; line = in.readLine(); line != null)
string.append(line).append("\n");
in.close();
data = line.toString();
}
catch (IOException ioe) {
System.err.println("Oops: " + ioe.getMessage());
}
Just remember to import java.io.* first.
This will replace all newlines in the file with \n, because I don't think there is any way to get the separator used in the file.