Text processing in java android - java

I have a file that looks similar to this
12345 one
12345 two
12345 three
.......
Question is how can i get all of the values from second row and store them in a String[]
i know how to read file in java just dont know how to cut the second row

1. Store Each line from the file into an ArrayList<String>, its more flexible than String[] array.
2. Then access the line you need by get() method of ArrayList
Eg:
ArraList<String> arr = new ArrayList<String>();
//Now add each lines into this arr ArrayList
arr.get(1); // Getting the Second Line from the file
`

You can split the file line by new line.
String [] names = fileString.split("\n");

Ok this is what i did but it skips first line
FileInputStream fstream = new FileInputStream("/sys..........");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
strLine = br.readLine();
while ((strLine = br.readLine()) != null) {
delims = strLine.split(" ");
first = delims[1];
where.add(first);
}
in.close();
From example above it contains only "two" and "three"

Related

Only add unique elements to arraylist in Java

I am currently writing a java program that takes data from a text file and adds to to an array list. My problem is, that every time I run the program, the arraylist keeps updating and has duplicate elements - I would like each element to only appear once.
`
BufferedReader br = new BufferedReader(new FileReader("s.txt"));
for (String line = br.readLine(); line != null; line = br.readLine()) {
if(!listID.contains(Integer.parseInt(line))){
listID.add(Integer.parseInt(line));
}
for(int i=0;i<listID.size();i++){
// do stuff
}
`
I have tried to use does not contain but it isnt working.
Does this work for you?
Set<Integer> set = new HashSet();
BufferedReader br = new BufferedReader(new FileReader("s.txt"));
for (String line = br.readLine(); line != null; line = br.readLine()) {
set.add(Integer.parseInt(line));
for(int i=0;i<listID.size();i++){
// do stuff
}
}

BufferedReader multiple lines as one String

I am trying to read multiple lines from a file into an ArrayList as a String.
What I aim to do is to make it so the program reads from a file line by line until the reader sees a specific symbol (- in this case) and saves those rows as one single String. the code below makes every row a new string that it later adds to the list instead.
BufferedReader br = null;
br = new BufferedReader(new FileReader(file));
String read;
while ((read = br.readLine()) != null) {
String[] splited = read.split("-");
carList.add(Arrays.toString(splited));
}
for (String carList2 : carList) {
System.out.println(carList2);
System.out.println("x");
}
First, you need to check if the read line contains "-".
If it doesn't, concatenate the line with the previous ones.
If it does, concatenate only the first part of the line with the previous line.
This is a quick implementation:
BufferedReader br = null;
br = new BufferedReader(new FileReader(file));
String read;
String concatenatedLine = "";
while ((read = br.readLine()) != null) {
String[] splited = read.split("-");
// if line doesn't contains "-", splited[0] and read are equals
concatenatedLine += splited[0];
if (splited.length > 1) {
// if read line contains "-", there will be more than 1 element
carList.add(Arrays.toString(splited)); // add to the list
// store the second part of the line, in order to add it to the next ones
concatenatedLine = splited[1];
}
}
Note the output could not be what is expected if a line contains more than one -.
Also, concatenating String using + is not the best way to do it, but I let you find out more about that.
It's not very clear for me what is the output you desire.
If you would like to have each customer on one string without "-"
then you could try the following code:
while ((read = br.readLine()) != null) {
String splited = read.replace("-", " ");
carList.add(splited);
}

Remove spaces only certain places not everywhere

I am taking in txt from a txt file and trying to store it in an arraylist. In the txt file the which mean ballot are not together instead the teacher placed it on a separate line. So we have to get all of the ballots together but i am not able to get them to be all together she placed the first ballot on the line like in example below. And we have to make the rest of them together. I am using a fileinputstream to collect the txt from the textfile.
the text looks like this :
person 1
person 2
person 3
<b> 1 2 3
<b>
1
3
2
I want it to look like this
person 1
person 2
person 3
<b> 1 2 3
<b> 1 3 2
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter file name: ");
Scanner keyboard = new Scanner(System.in);
String fileName = keyboard.next();
File file = new File(fileName);
ArrayList<String> ballot;
ballot = new ArrayList<String>();
FileInputStream fstream = new FileInputStream(fileName);
DataInputStream ds = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(ds));
// Pattern p;
// Matcher m;
String strLine;
String inputText = "";
String newline = System.getProperty("line.separator");
while ((strLine = br.readLine()) != null) {
ballot.add(strLine);
}
You need to use a StringBuilder sb = new StringBuilder();. Each time you have a token String t, call sb.append(t.trim()).append(' ');. When done with parsing your file, call sb.toString();. If you want to add newlines here and there, use sb.append('\n');.
If you want an array of your tokens, you should use an ArrayList<String> al = new ArrayList<String>; Each time you have a set of token s making a line, use al.add(s); When done, call String[] result = al.toArray(new String[al.length]); You will need to concatenate your set of tokens into s for each line.

Java - Parsing Text File

I have an input text file in this format:
<target1> : <dep1> <dep2> ...
<target2> : <dep1> <dep2> ...
...
And a method that takes two parameters
function(target, dep);
I need to get this parsing to call my method with each target and dep eg:
function(target1, dep1);
function(target1, dep2);
function(target1, ...);
function(target2, dep1);
function(target2, dep2);
function(target2, ...);
What would be the most efficient way to call function(target,dep) on each line of a text file? I tried fooling around with the scanner and string.split but was unsuccessful. I'm stumped.
Thanks.
Read line into String myLine
split myLine on : into String[] array1
split array1[1] on ' ' into String[] array2
Iterate through array2 and call function(array1[0], array2[i])
So ...
FileReader input = new FileReader("myFile");
BufferedReader bufRead = new BufferedReader(input);
String myLine = null;
while ( (myLine = bufRead.readLine()) != null)
{
String[] array1 = myLine.split(":");
// check to make sure you have valid data
String[] array2 = array1[1].split(" ");
for (int i = 0; i < array2.length; i++)
function(array1[0], array2[i]);
}
The firstly you have to read line from file and after this split read line, so your code should be like:
FileInputStream fstream = new FileInputStream("your file name");
// or using Scaner
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// split string and call your function
}

How to read a String (file) to array in java

Suppose there is a file named as SUN.txt
File contains : a,b,dd,ss,
I want to make dynamic array depending upon the number of attributes in file.
If ther is a char after comma then array will be of 0-4 i.e of length 5.
In the above mentioned case there is no Char which returns 0-3 Array of length 4. I want to read the NULL after comma too.
How do i do that?
Sundhas
You should think about
Reading the file into a String
Splitting the file by separator ','
Using a list for adding the characters and convert the list to an array, when the list is filled
As Markus said, you want to do something like this..
//Create a buffred reader so that you can read in the file
BufferedReader reader = new BufferedReader(new FileReader(new File(
"\\SUN.txt")));
//The StringBuffer will be used to create a string if your file has multiple lines
StringBuffer sb = new StringBuffer();
String line;
while((line = reader.readLine())!= null)
{
sb.append(line);
}
//We now split the line on the "," to get a string array of the values
String [] store = sb.toString().split(",");
I do not quite understand why you would want the NULL after the comma? I am assuming that you mean after the last comma you would like that to be null in your array? I do not quite see the point in that but that is not what the question is.
If that is the case you wont read in a NULL, if after the comma there was a space, you could read that in.
If you would like a NULL you would have to add it in yourself at the end so you could do something like
//Create a buffred reader so that you can read in the file
BufferedReader reader = new BufferedReader(new FileReader(new File(
"\\SUN.txt")));
//Use an arraylist to store the values including nulls
ArrayList<String> store = new ArrayList<String>();
String line;
while((line = reader.readLine())!= null)
{
String [] splitLine = line.split(",");
for(String x : splitLine)
{
store.add(line);
}
//This tests to see if the last character of the line is , and will add a null into the array list
if(line.endsWith(","))
store.add(null);
}
String [] storeWithNull = store.toArray();
Well if you want want to simply open the file and store the content in a array of string then
1) open the file into a string
2) split the string using a regex "," http://download.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#split(java.lang.String)
but I'm curious why you can't use a String file directly ?
For your datatructure, use a list of arrays. Each list entry is a line of your textfile, each entry is an array that holds the comma separated values:
List<String[]> data = new ArrayList<String[]>();
String line = readNextLine(); // custom method, to be implemented
while (line != null) {
data.add(line.split(","));
line = readNextLine();
}
(assuming, your file contains 1..n lines of comma separated values)
You may want to have it like this:
"a,b,c,d," -> {"a", "b", "c", "d", null}
Here's a suggestion how to solve that problem:
List<String[]> data = new ArrayList<String[]>();
String line = readNextLine(); // custom method, to be implemented
while (line != null) {
String[] values = new String[5];
String[] pieces = line.split(",");
for (int i = 0; i<pieces.length; i++)
values[i] = pieces[i];
data.add(values);
line = readNextLine();
}
its seems like a CSV file something like this will work assuming it has 5 lines and 5 values
String [][] value = new String [5][5];
File file = new File("SUN.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
int row = 0;
int col = 0;
while((line = br.readLine()) != null ){
StringTokenizer s = new StringTokenizer(line,",");
while (s.hasMoreTokens()){
value[row][col] = s.nextToken();
col++;
}
col = 0;
row++;
}
i havent tested this code
Read the file, using BufferedReader, one line at the time.
Use split(",", -1) to convert to an array of String[] including also empty strings beyond the last comma as part of your array.
Load the String[] parts into a List.

Categories