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
}
Related
I am trying to extract a specific content from text file by using delimiters. This is my code :
File file = new File("C:\\Inputfiles\\message.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
while ((st=br.readLine()) != null) {
String[] strings = StringUtils.split(st, "------------");
System.out.println(strings);}
But as a result, each and everyline is getting splitted by delimiter and saved as array.
Can anyone suggest how I can save the contents from file as a single string, so I can get limited number of lines only as Array.
You can use StringBuilder or StringBuffer to do that.
File file = new File("C:\\Inputfiles\\message.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
while ((st=br.readLine()) != null) {
String[] strings = StringUtils.split(st, "------------");
StringBuilder singleString = new StringBuilder();
for(String s : strings){
singleString.append(s);
}
System.out.println(singleString.toString());
}
Thanks All,
I did using below changes
String contents = new String(Files.readAllBytes(Paths.get("C:\\Inputfiles\\message1.txt")));
String[] splitted = StringUtils.split(contents, "-------");
for(int i=0;i<splitted.length;i++)
System.out.println(splitted[i]);
ArrayList storeList = new ArrayList<USCrimeClass>;
FileInputStream fstream = new FileInputStream(inFile);
try ( // Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream)) {
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
// Read File Line By Line
strLine = br.readLine();// skip first line
while ((strLine = br.readLine()) != null) {
// lines
storeList.add(storeToCrimeObjin(strLine));
}
// Close the input stream
There are missing () in new ArrayList<USCrimeClass>; it should be:
ArrayList storeList = new ArrayList<USCrimeClass>();
ArrayList<USCrimeClass> storeList = new ArrayList<>();
The diamond operator <> is now in the latter part of the statement.
Apart from that, I'd say #gawi is right.
I only want to read the first line of a text file and put that first line in a string array.
This is what I have but its reading the whole file.
ex text in myTextFile:
Header1,Header2,Header3,Header4,Header5
1,2,3,4,5
6,7,8,9,10
String line= System.getProperty("line.separator");
String strArray[] = new String[5];
String text = null;
BufferedReader brTest = new BufferedReader(new FileReader(myTextFile));
text = brTest .readLine();
while (text != line) {
System.out.println("text = " + text );
strArray= text.split(",");
}
use BufferedReader.readLine() to get the first line.
BufferedReader brTest = new BufferedReader(new FileReader(myTextFile));
text = brTest .readLine();
System.out.println("Firstline is : " + text);
If I understand you, then
String text = brTest.readLine();
// Stop. text is the first line.
System.out.println(text);
String[] strArray = text.split(",");
System.out.println(Arrays.toString(strArray));
With Java 8 and java.nio you can also do the following:
String myTextFile = "path/to/your/file.txt";
Path myPath = Paths.get(myTextFile);
String[] strArray = Files.lines(myPath)
.map(s -> s.split(","))
.findFirst()
.get();
If TAsks assumption is correct, you can realize that with an additional
.filter(s -> !s.equals(""))
Also, beside of all other solutions presented here, you could use guava utility class (Files), like below:
import com.google.common.io.Files;
//...
String firstLine = Files.asCharSource(myTextFile).readFirstLine();
I think you are trying to get one line only if it's not empty.
You can use
while ((text=brTest .readLine())!=null){
if(!text.equals("")){//Ommit Empty lines
System.out.println("text = " + text );
strArray= text.split(",");
System.out.println(Arrays.toString(strArray));
break;
}
}
Use this
BuffereedReader reader = new BufferedReader(new FileReader(textFile));
StringBuilder builder = new StringBuilder();
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
break;
}
if(sb.toString.trim().length!=0)
System.out.println("first line"+sb.toString);
I hope this will help someone
to read the first line:
public static String getFirstLine() throws IOException {
BufferedReader br = new BufferedReader(new FileReader("C:\\testing.txt"));
String line = br.readLine();
br.close();
return line;
}
to read the whole text:
public static String getText() throws IOException {
BufferedReader br = new BufferedReader(new FileReader("C:\\testing.txt"));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line).append("\n");
line = br.readLine();
}
String fileAsString = sb.toString();
br.close();
return fileAsString;
}
You need to change the condition of your loop
String[] nextLine;
while((nextLine = brTest.readLine()) != null) {
...
}
ReadLine reads each line from beginning up to the occurrence of \r andor \n
You can also use tokenizer to split the string
String[] test = "this is a test".split("\\s");
In addition it seems the file is of type CSV if it is please mention that in the question.
I must split this input from file into vectors and add to a vectors.
File input
1,375,seller
1,375,sellers
1,375,send
1,375,sister
1,375,south
1,375,specific
1,375,spoiler
1,375,stamp
1,375,state
1,375,stop
1,375,talked
1,375,tenant
1,375,today
1,375,told
FileInputStream fstream = new FileInputStream("e://inputfile.txt");
// Use DataInputStream to read binary NOT text.
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
while ((strLine = br.readLine()) != null)
{
Vector dataPoints = new Vector();
dataPoints.add(br);
dataPoints.add(new DataPoint());
}
------ public DataPoint(double x, double y, String name) this is the method
How to split the string into double and string and give a input to the vector?
Use String#split(String):
Vector<DataPoint> dataPoints = new Vector<DataPoint>();
while ((strLine = br.readLine()) != null) {
String[] array = strLine.split(",");
dataPoints.add(new DataPoint(Double.parseDouble(array[0]), Double.parseDouble(array[1]), array[2]));
}
Just split the String returned from the Bufferedreader using String.split() using , as a delimiter. and also consider using an ArrayList instead of Vector, unless you care about thread safety and also make your collections generic.
Vector<DataPoint> dataPoints = new Vector<DataPoint>();
while ((strLine = br.readLine()) != null)
{
String[] arr = strLine.split(",");
DataPoint point = new DataPoint(Double.valueOf(arr[0]), Double.valueOf(arr[1]), arr[2]);
dataPoints.add(point);
}
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"