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
Related
I'm really new in Java and I'm trying to figure out how to read a line from .txt file in SD card. The code below doesn't seem to work since it returns an empty result.
public static final String filePath = Environment.getExternalStorageDirectory().getPath();
public static String getProfileInfo() {
String line = "";
StringBuilder sb = new StringBuilder();
try{
File unzippedText = new File(filePath + "profile.txt");
BufferedReader text = new BufferedReader(new FileReader(unzippedText));
sb.append(line);
text.close();
}catch(Exception e){
e.printStackTrace();
}
return sb.toString();
}
Thanks
This code is not going to do anything
sb.append(line);
line is still equal to ""
try reading using the BufferedReader.readLine
line = text.readLine (); // first line only
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 have one file to read which is like this
mytxt.txt
1234 http://www.abc.com
8754 http://www.xyz.com
I tried with this
try {
// make a 'file' object
File file = new File("e:/mytxt.txt");
// Get data from this file using a file reader.
FileReader fr = new FileReader(file);
// To store the contents read via File Reader
BufferedReader br = new BufferedReader(fr);
// Read br and store a line in 'data', print data
String data;
while((data = br.readLine()) != null)
{
//data = br.readLine( );
System.out.println(data);
}
} catch(IOException e) {
System.out.println("bad !");
}
I used this but the actual question is I want to read one this two charachter one by one and then appens the digit to the link which I'll read as string.
Can anyone tell me how I am suppose to do that..?
any help would be appreciated.
Parse the line you are reading, search for the first white space (I'm assuming you have only one space separating your digit and your url) something like this:
try {
// make a 'file' object
File file = new File("e:/mytxt.txt");
// Get data from this file using a file reader.
FileReader fr = new FileReader(file);
// To store the contents read via File Reader
BufferedReader br = new BufferedReader(fr);
// Read br and store a line in 'data', print data
String data;
while((data = br.readLine()) != null)
{
int posWhite = data.indexOf(' ');
String digit = data.substring(0, posWhite);
String url = data.substring(posWhite + 1);
System.out.println(url + "/" + digit);
}
} catch(IOException e) {
System.out.println("bad !");
}
Is this what you want?
while((data = br.readLine()) != null)
{
String[] data=br.readLine().split();
if(data!=null&&data.length==2)
{
System.out.println(data[1]+"/"+data[0]);
}else
{
System.out.println("bad string!");
}
}
In the while((data = br.readLine()) != null), make the code like this:
String tmpData[] = data.split(" ");
System.out.println(tmpData[1] + "/" + tmpData[0]);
Is it possible (and wise) to check if a value exists in an external text file.
So if i have a file: bankcodes.txt that contains the next lines:
INGB
ABNA
...
Is it possible to check if a value is present in this file?
The reason is that these values can change and need to be easily changed whitout making a new jar file.
If there is another, wiser way of doing this i would like to hear it too.
From here:
https://stackoverflow.com/a/4716623/110933
Read contents of file line by line and check the value you get for "line" for the value you want:
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append("\n");
line = br.readLine();
}
String everything = sb.toString();
} finally {
br.close();
}
Give example how i did it , while File.txt -> our text and ourValue it the one we searching
String ourValue="value"
BufferedReader br = new BufferedReader(new FileReader("File.txt"));
String line = br.readLine();
boolean exist = false;
while (line != null&&!exist) {
if (ourValue.equals(line)) {
exist = true;
} else {
line = br.readLine();
}
}
System.out.println("the value " +ourValue+" exist in the Text? "+ exist);
}