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.
Related
So I am trying to return a large string array of length 200, but the code I am using only returns 15/ sets the array length to 15 during execution when it has been initiated to reserve 200 spaces as the size of the array may change so I made it big to try and accommodate different sizes.
public static String[] populateArray(String fileName)
{
String [] record = new String [200]; // array length is 200
try
{
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line = null;
int counter = 0;
int arrayLength = 0; // using this to check length during execution
while((line = bufferedReader.readLine())!= null && counter < 200)
{
record[counter] = line;
counter +=1;
arrayLength = record[0].length(); // the file contains 20 lines to input here but
only does 15
}
bufferedReader.close();
}
catch (IOException ex)
{
System.out.println("There was an error while trying to access the file");
}
return record;
}
Is the first line of the file 15 characters long? It looks like you're finding the length of that string, instead of the amount of lines read in. Furthermore, you set the arrayLength variable to the same value, in each loop iteration.
If you want to count lines read, I suggest just printing the counter variable.
The code you posted seems to work, reading in all the file's lines (With my test file). I'm guessing, therefore, that your issue was with looking at the wrong variable in order to verify what was read in.
I've read number of such questions but they are all about reading inputs from a txt file. I want to read input from user and not from the file.
I've input like following:
6 //number of total Strings to store in array
babu
anand
rani
aarti
nandu
rani
I've tried the following code to take such input in a String array:
int n = in.nextInt(); // n= 6 here
String[] s = new String[n]; //String array of size 6 here
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try{
s = br.readLine().split("\\s");
}
catch(Exception e){
System.out.println(e);
}
Is the regex provided to the split() is correct or not? What I'm missing here? If this is not correct approach than what should I do for this problem?
Regex are using backslashes (\) while you used slashes //s, correct one is \\s.
But this split is not needed, you just need the readLine, and you will get what you need (assuming you don't want to split words in the line).
You should use a loop to read all the data (and get rid of Scanner, that you appear to have in the in variable):
String[] s = null
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in)) {
int n = Integer.parseInt(br.readLine());
for (int line = 0; line < n; line++) {
s[line] = br.readLine();
}
} catch(Exception e){
System.out.println(e);
}
Move the third line before the first one.
Then use this in your new second line:
int n = Integer.parseInt(br.readLine());
And, of course, you need a loop to put your input strings into an array.
This should help.
I was looking through a lot of diffrent subjects here on stackoverflow but couldn't find anything helpful so far :/
So this is my problem. I am writing a filecopier. The problem occurs already at reading the file. My test docoument got 3 lines of random text. All those 3 lines should get written in a string array. The problem is that only the 2nd line of the textdocument gets written in the array and I can't figure out why. Already debugged it, but didn't get me any further.
I know there are diffrent solutions for a filecopier with diffrent classes etc. But I would really like to get it running with the classes I used here.
String[] array = new String[5];
String datei = "test.txt";
public String[] readfile() throws FileNotFoundException {
FileReader fr = new FileReader(datei);
BufferedReader bf = new BufferedReader(fr);
try {
int i=0;
//String Zeile = bf.readLine();
while(bf.readLine() != null){
array[i] = bf.readLine();
// System.out.println(array[i]); This line is for testing
i++;
}
bf.close();
} catch (IOException e) {
e.printStackTrace();
}
return array;
You're calling readLine() twice for each iteration of the loop, thereby discarding every other line. You need to capture the value returned by every call to readLine(), because each readLine() call advances the reader's position in the file.
Here's the idiomatic solution:
String line;
while((line = bf.readLine()) != null){
array[i] = line;
i++;
}
Here you read 2 lines:
while(bf.readLine() != null){
array[i] = bf.readLine();
// System.out.println(array[i]); This line is for testing
i++;
}
You have to change your Code to:
String line = null;
while((line =bf.readLine()) != null){
array[i] = line;
// System.out.println(array[i]); This line is for testing
i++;
}
The problem is here :
while(bf.readLine() != null)
readLine() reads a line and returns the same at the same time it moves to the next line.
So instead of just checking if the returned value was null also store it.
String txt = null;
while((txt = bf.readLine()) != null)
array[i++] = txt;
I think its because you are calling readLine() twice. First time in the loop, and then second time when you put it in the array. So, it reads a line at the beginning of the loop (line 1), then first line of code inside the loop (line 2 that you see)
I am use Stream.
Not a. This form only applies to reading text files.
BufferedReader bf = new BufferedReader(fr);
// ...
List<String> lines = bf.lines().collect(Collectors.toList());
I want to write a file in multiple line in a file. for example:
first line: a b c d e f g h i
second line: j k l m n o p q r
third line: s t u v w x y z 1
but the code I made cannot do so. it only prints on one line every time I try to write in it. Here's my code:
FileOutputStream write = new FileOutputStream ("file.txt");
PrintStream print = new PrintStream (write);
BufferedReader in = new BufferedReader(new FileReader(data));
String read;
while ((read = in.readLine()) != null) {
String[] splited = read.split("\n");
for (int z = 0; z<splited.length; z++){
print.print(splited[z]+" ");
}
}
print.println();
how can i fix this?
You need to move print.println() inside the while loop.
The correct way is as follows :
while ((read = in.readLine()) != null) {
String[] splited = read.split("\n");
for (int z = 0; z<splited.length; z++){
print.print(splited[z]+" ");
}
print.println(); // correct place for println
}
So first of all, readLine reads one line, up to a newline, so there is no need to call split("\n") because it will always return the string itself.
Second, you never write a newline to the output file, so it ends up having all the lines unrolled in one. You can just modify the line print.print(splited[z] + " "); to print.print(splited[z] + "\n");.
I have altered your code in a few ways to improve readability and performance.
I am now using a BufferedWriter instead of a PrintStream, which has a nice method for writing newlines.
I am using try-with-resources. This is a Java 7+ feature that automatically closes connections, streams, and buffers for you. In your current code I don't see you closing either the reader or the writer. For such a small program this is not a big deal, but it is good practice to close them.
I used a for loop instead of a while loop. This is a nice trick I picked up that saves me from defining read in a higher scope than I need it (scope-creep).
-
try (BufferedWriter writer = new BufferedWriter(new FileWriter("file.txt"));
BufferedReader reader = new BufferedReader(new FileReader(data)))
{
for (String read = reader.readLine(); read != null; read = reader.readLine()) {
writer.append(read);
writer.newLine();
}
}
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.