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.
Related
I want to by reading the data of a file to split the results based on .split(",") in another words for this particular example i want to have 2 Indexes with each containing up to 5 informations which i would also like to acces with the .[0] and .[1] Method.
the File with the Data.
File Reading Method.
public void fileReading(ActionEvent event) throws IOException {
File file = new File("src/DateSpeicher/datenSpeicher.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
while ((st = br.readLine()) != null) {
System.out.println(st);
}
}
The method does work very greatly however, i wonder how can i split those two in two Indexes or String arrays which both can be accessed through respective indecies [0], [1]. For first data in the firm array - 655464 [0][0] for last in the second Array [1][4].
My approach:
1. Making an ArrayList for every ,
2. Adding data till ","
Issue: eventho approach above works, you cant do such things as array1[0] - it gives an error, however the index method is crucial.
How can i solve this problem?
Path path = Paths.get("src/DateSpeicher/datenSpeicher.txt"); // Or:
Path path = Paths.get(new URL("/DateSpeicher/datenSpeicher.txt").toURI());
Either two Strings, and then handling them:
String content = new String(Files.readAllBytes(path), Charset.defaultCharset());
String[] data = content.split(",\\R");
or a list of lists:
List<String> lines = Files.readAllLines(path, Charset.defaultCharset());
// Result:
List<List<String>> lists = new ArrayList<>();
List<String> newList = null;
boolean addNewList = true;
for (int i = 0; i < lines.size(); ++i) {
if (addNewList) {
newList = new ArrayList<>();
lists.add(newList);
addNewList = false;
}
String line = lines.get(i);
if (line.endsWith(",")) {
line = line.substring(0, line.length() - 1);
addNewList = true;
}
newList.add(line);
}
-Java- I have a text file in which I am storing ID number, First Name, and Last Name on each line. I'm using BufferedReader to display the text files line by line. However I then need to take the ID number only from each line and store it into an array. If anyone can help it would be greatly appreciated.
As you said, you are already printing the line read from file, next you just need to split the line with the delimiter you have in file. Assuming you have comma as the delimiter, all you need to do is, split the line with comma and access the first element and store it in the List,
Here is the sample code,
public static void main(String[] args) throws Exception {
try(BufferedReader br = new BufferedReader(new FileReader("filename.txt"))) {
String line = null;
List<String> idList = new ArrayList<String>();
while((line = br.readLine()) != null) {
System.out.println(line); // you already printing it
String[] tokens = line.split("\\s*,\\s*"); // assuming your line is like this --> 123, Pushpesh, Rajwanshi
if (tokens.length > 0) {
idList.add(tokens[0]); // ID will be accessed at zero index
}
}
idList.forEach(System.out::println);
}
}
Using Java8 and above, you can do it in one liner.
List<String> idList = Files.lines(Paths.get("filename.txt")).filter(x -> x.trim().length() > 0)
.map(x -> x.split("\\s*,\\s*")).map(x -> x[0]).collect(Collectors.toList());
idList.forEach(System.out::println);
List<String> idList = Files.readAllLines(
Paths.get(FILE_PATH),
Charset.defaultCharset()
).stream()
.map(line -> line.split(SEPARATOR)[DATA_INDEX])
.collect(Collectors.toList());
FILE_PATH = file location ("c://users//..").
SEPARATOR = which separate datas (1:NAME:LAST_NAME < the separator for this ex = ":").
DATA_INDEX = index of data (1:NAME:LAST_NAME < the id index for this ex = 0).
I have a file text called messages.txt as following:
6107586533 44335557075557777
4848675309 53366 6699044404666804448
6107584096 94466602777330999666887770223377778077778 883 336687777
First column represents the numbers of recipient and second column represents the digit-coded message(and I will use a decoder method to decode the second column digits, which I have already created).I used the following method to read the file text:
public void readMessagesFromFile() throws Exception{
BufferedReader in = new BufferedReader(new FileReader("messages.txt"));
String str;
List<String> list = new ArrayList<String>();
while((str = in.readLine()) != null){
list.add(str);
}
String[] stringArr = list.toArray(new String[3]);
for (String x: stringArr) {
System.out.print(x);
}
}
However, it stores everything(as it should be) like the following:
6107586533 443355570755577774848675309 53366 66990444046668044486107584096 94466602777330999666887770223377778077778 883 336687777
How can I read and store only the following portion:
44335557075557777
53366 6699044404666804448
94466602777330999666887770223377778077778 883 336687777
I want to read and store as in lines,i.e. each row in the second column will be assigned to each index of the array), just want to exclude the first column when I store the second column.
This will split the line and keep everything after the first token
List<String> list = new ArrayList<String>();
while((str = in.readLine()) != null){
String[] temp = str.trim().split("\\s+",2);
list.add(temp[1]);
}
The call to trim is in case there are leading blanks.
As to the conversion to an array your code, you don't need it, you can iterate over the list.
for (String s : list)
{
System.out.println(s);
}
I need to process a big text file, there are almost 400 column in each line, and almost 800000 lines in the file, the format of each line in the file is like:
340,9,2,3........5,2,LA
what I want to do is, for each line, if the last column is LA, then print the first column of this line.
i write a simple program to do it
BufferedReader bufr = new BufferedReader(new FileReader ("A.txt"));
BufferedWriter bufw = new BufferedWriter(new FileWriter ("LA.txt"));
String line = null;
while ((line = bufr.readLine()) != null) {
String [] text = new String [388];
text = line.split(",");
if (text [387] == args[2]) {
bufw.write(text[0]);
bufw.newLine();
bufw.flush();
}
}
bufw.close();
bufr.close();
but it seems the length of an array cant be that big, i received a java.lang.ArrayIndexOutOfBoundsException
since i'm using split(",") in order to get the last column of a line, and it will be out of array bounds, how can I do with it? thanks.
text does not need to be initialized, String.split will create a correctly sized array:
String[] text = line.split(",");
You're also comparing Strings using reference equality (==). You should be using .equals():
if (text[387].equals(args[2])) { ... }
You're probably getting java.lang.ArrayIndexOutOfBoundsException because the the index 387 is too big. If you want to get last element, use this:
text[text.length - 1]
Modify and try this
String [] text = line.split(",");
if (text [text.length - 1].equals(args[2])) {
bufw.write(text[0]);
bufw.newLine();
bufw.flush();
}
Assuming args[2] is LA.
String [] text;
Change your code to this. You don't need to initialize a size. When the String.split method executes it will automatically initialize the correct size for your array.
If you just need the first and the last column, then there is no need to create an array out of the current line.
You could do something like this:
final String test = "340,9,2,354,63,5,5,45,634,5,5,2,LA";
final char delimiter = ',';
final String lastColumn = test.substring(test.lastIndexOf(delimiter) + 1);
if (lastColumn.equals("LA")) {
final String firstColumn = test.substring(0, test.indexOf(delimiter));
System.out.println(firstColumn);
}
This code extracts the last column first and tests it. If it matches "LA", then it extract the first column. It will ignore the remaining content of the line.
Your code would be:
BufferedReader bufr = new BufferedReader(new FileReader ("A.txt"));
BufferedWriter bufw = new BufferedWriter(new FileWriter ("LA.txt"));
String line = null;
while ((line = bufr.readLine()) != null) {
final String lastColumn = line.substring(line.lastIndexOf(delimiter) + 1);
if (lastColumn.equals(args[2])) {
bufw.write(line.substring(0, line.indexOf(delimiter)));
bufw.newLine();
bufw.flush();
}
}
bufw.close();
bufr.close();
(this code is not tested yet, but you get the idea :))
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"