Let's say I have a series of numbers like...
1 2 3 4
5 6 7 8
9 0
How could I step through each int, but stop when I reach a new line? I'm currently using nextInt() and I know that nextLine() will detect the new line, but I'm not sure how to piece that together. Is it best to take the entire line, and parse the string into separate ints? Or is there a more fluid method of doing this?
For my example, I would want the program to store 1 2 3 4, 5 6 7 8, 9 0 all in their own separate array.
For more clarification, I'm using the java.util.Scanner and I'm reading a text file.
If you want to use Scanner, read the entire line into a String, and then construct a Scanner on the String.
You can open the text file in read mode and read the entire line with readLine() method.
Then you can split the line read with the space ( ' ' ) character which will automatically give you an array.
You can do this till the end of file.
import java.io.*;
class FileRead
{
public static void main(String args[])
{
try{
// Open the file
FileInputStream fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
delimiter = " ";
int myArr[];
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
myArr = strLine.split(delimiter);
// store this array into some global array or process it in the way you want.
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
Hope this helps.
Related
This question already has answers here:
How do I split a string in Java?
(39 answers)
Closed 5 years ago.
I am trying to read text file with 3 lines:
10
PA/123#PV/573#Au/927#DT/948#HY/719#ZR/741#bT/467#LR/499#Xk/853#kD/976#
15.23#25.0#17.82#95.99#23.65#156.99#72.85#62.99#112.0#55.99#
So far in my main method I have:
`String fileName = "productData.txt";
String line = null;
try {
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader =
new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close();
}
catch(FileNotFoundException e) {
System.out.println(e);
}
catch(IOException e) {
e.printStackTrace();
}`
But Im not sure how I would go on with using the String DELIMITER = "#";
In the text file Line 1: is applied to number of types of product, Line 2: are product codes separated by #, and in Line 3: Price per unit of the corresponding products separated by #.
So Im looking for kind of format PA/123 Costs 15.23. How would I do that?
You can you line.split('#'); to get an array of Strings. This array contains your 10 elements.
Then you have two arrays of size 10. So firstArray[0] contains the name of the first product and secondArray[0] contains the price of it.
I'm trying to write a Java application that reads a text file. Suppose I have a text file beg.txt which contains text:
I am a beginner
When the user enters word number 4, the program has to print word 'beginner'.
How can I do this in Java, please?
First give a try before asking this.
Just for your help. Try following steps, this is not the only way.
Read your file
Split string to a string array using space
Print array[your choice - 1]
BufferedReader br = null;
String[] str;
try {
String sCurrentLine;
StringBuilder sb = new StringBuilder();
br = new BufferedReader(new FileReader("C:\\testing.txt"));
while ((sCurrentLine = br.readLine()) != null) {
sb.append(sCurrentLine);
}
str = sb.toString.split(" ");
} catch (IOException e) {
e.printStackTrace();
}
if user enters 4 then you can use array 'str' like this :
String result = str[userEnteredValue - 1];
Note: the above code will work only when the file will contain space delimitted characters.
File read=new File("D:\\Test.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(read),Charset.forName("UTF-8")));
String news = reader.readLine();
String[] records = news.split(" ");
if your input is 4
and get records[4]
Well, the basic process will be something like the following:
Load the text file
Get user input
Process text file with parameters from user
Step 1 will depend on which version of Java you're using. If Java 7, I'd look at nio2. Java 6 has other options. Or you could you Guava or Apache Commons. Since the processing required is minimal, I would store the output of this step as a simple String.
Getting the user input can be done in a number of ways, but one option is to use a Scanner.
Finally, processing the file can be done by using String.split() with a simple regex and then picking the correct element from the resulting array.
have some problem reading a file in java and save each element into 2 arrays.
my txt is made like this
2,3
5
4
2
3
1
where the first line is the lenght of two array A=2 and B=3 and then the element of each array. I don't know how to save them into A and B and initialized the array with their lenght.
At the end each array will be A=[5,4] B=[2,3,1]
public static void main(String args[])
{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("prova.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != " ") {
String[] delims = strLine.split(",");
String m = delims[0];
String n = delims[1];
System.out.println("First word: "+m);
System.out.println("First word: "+n);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
this is what i made..i used System.out.println.... just to print in console it's not necessary...Someone can help me, give me some advice?
thanks in advance
Again, break the big problem into little steps, solve each step.
Read first line.
Parse first line to get sizes of the 2 arrays.
Create the arrays.
Loop first array length times and fill the first array.
Loop second array length times and fill second array.
Close BufferedReader in a finally block (make sure to declare it before the try block).
Show results.
Match this answer with the steps outlined in #Hovercraft's answer
String strLine = br.readLine(); // step 1
if (strLine != null) {
String[] delims = strLine.split(","); // step 2
// step 3
int[] a = new int[Integer.parseInt(delims[0])];
int[] b = new int[Integer.parseInt(delims[1])];
// step 4
for (int i=0; i < a.length; i++)
a[i] = Integer.parseInt(br.readLine());
// step 5
for (int i=0; i < b.length; i++)
b[i] = Integer.parseInt(br.readLine());
br.close(); // step 6
// step 7
System.out.println(Arrays.toString(a));
System.out.println(Arrays.toString(b));
}
Notice, I called br.close(). With in.close() you're closing the inner stream only and that leaves BufferedReader still open. But closing the outer wrapper stream closes all the wrapped inner streams automatically. Note, that clean-up code like this should always go in a finally block.
Also, there's no need to have DataInputStream and InputStreamReader in the chain. Just wrap BufferedReader around a FileReader directly.
If all these classes are having you a bit confused; just remember Stream classes are used for reading at the byte level and Reader classes are used to read at character level. So, you only need Readers here.
This question already has answers here:
Java: Reading a file into an array
(5 answers)
Closed 1 year ago.
I'll try to be as clear as possible but pardon me if my question is not perfect.
I have a txt file with several lines of data. example:
123 ralph bose 20000 200 1 2
256 ed shane 30000 100 2 4
...
I need to read each line sequentially and pass it back to a method in a separate class for processing. I know how to break down each line into elements by using StringTokenizer.
However, i'm not sure how to read one line at a time, pass back the elements to the other class and then, once the processing is done, to read the NEXT line. Method cooperation between my classes works fine (tested) but how do i read one line at a time?
I was thinking of creating an array where each line would be an array element but as the number of lines will be unknown i cannot create an array as i don't know its final length.
Thanks
Baba
EDIT
rough setup :
Class A
end_of_file = f1.readRecord(emp);
if(!end_of_file)
{
slip.printPay(slipWrite);
}
Class B
public boolean readRecord(Employee pers) throws IOException {
boolean eof = false ;
String line = in.readLine() ;
???
}
filename is never passed around
so up until here i can read the first line but i think i need a way to loop through the lines to read them one by one with back and forth between classes.
tricky...
There are lots of ways to read an entire line at a time; Scanner is probably easiest:
final Scanner s = new Scanner(yourFile);
while(s.hasNextLine()) {
final String line = s.nextLine();
YourClass.processLine(line);
}
void readLine(String fileName)
{
java.io.BufferedReader br = null;
try
{
br = new java.io.BufferedReader(new java.io.FileReader(fileName));
String line = null;
while(true)
{
line = br.readLine();
if(line == null)
break;
// process your line here
}
}catch(Exception e){
}finally{
if(br != null)
{
try{br.close();}catch(Exception e){}
}
}
}
Also if you want to split strings... use
String classes split method. for splitting depending on space... you can do ... line.split("\\s*")
Hope it works
how to search for a certain word in a text file in java?
Using buffered reader, I have this code, but I get a
java.lang.ArrayIndexOutOfBoundsException
Please help me determine what's wrong with my program.
System.out.println("Input name: ");
String tmp_name=input.nextLine();
try{
FileReader fr;
fr = new FileReader (new File("F:\\names.txt"));
BufferedReader br = new BufferedReader (fr);
String s;
while ((s = br.readLine()) != null) {
String[] st = s.split(" ");
String idfromtextfile=st[0];
String nemfromtextfile = st[1];
String scorefromtextfile=st[2];
if(nemfromtextfile.equals(tmp_name)){
System.out.println("found");
}else{
System.out.println("not found");
}
}
}catch(Exception e){ System.out.println(e);}
names.txt looks like this:
1
a
0
2
b
0
Your code expects each line in the file to have three space-separated words. So your file must look like this:
1 a 0
2 b 0
The ArrayIndexOutOfBoundsException occurs if there is a line in the file that does not have three space-separated words. For example, there might be an empty line in your file.
You could check this in your code like this:
if ( st.length != 3) {
System.err.println("The line \"" + s + "\" does not have three space-separated words.");
}
You can use the Pattern/Matcher combination described here, or try the Scanner. Use the Buffered reader like this :
BufferedReader in
= new BufferedReader(new FileReader("foo.in"));
and extract the string with in.toString()
If text is huge and you don't want to read it at once and keep in memory. You may constantly read a line with readLine(), and search each of the output line for a pattern.
Here is an example of how to do it using BufferedReader
link text