I am trying to create a matrix from a text file. The problem is that when the Buffered Reader function readline() is done parsing first line of file it comes to second line but the its reading it as empty which it is not.
void covar()
{
double [][]covar=new double[10][5];
int i=0;
int j=0;
try
{
FileInputStream fstream = new FileInputStream("class 1\\feature_vector.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String input;
while((input=br.readLine())!= null)
{
String [] temp=input.split(",");
//System.out.println(input.split(",").length);
covar[i][j]= new Double(temp[0]);
covar[i+1][j]=new Double(temp[1]);
covar[i+2][j]=new Double(temp[2]);
covar[i+3][j]=new Double(temp[3]);
covar[i+4][j]=new Double(temp[4]);
//i=0;
j++;
}
in.close();
}
catch(Exception e)
{
e.printStackTrace();
}
Above is the code. The file name is perfect and nothing is wrong with the stream thing. Can you guys help me out with what is wrong with this.
Here is the content of the file:
0.75,321.0,0.22429906,0.97507787,1.966202512778112
0.33333334,135.0,-0.014814815,1.0,5.323770568766052
0.64285713,311.0,0.025723472,1.0,4.764298570227433
0.6,188.0,0.03723404,1.0,4.7349608150168105
0.25,189.0,0.16931216,0.98941797,7.15681209803803
0.71428573,194.0,-0.26804122,0.96391755,5.1654456838422425
0.6,173.0,0.028901733,1.0,6.54275787030257
0.2857143,257.0,0.031128405,1.0,6.095356508899233
0.23076923,197.0,-0.04568528,1.0,3.784908227189768
0.18181819,231.0,0.17316018,0.987013,5.956322938602553
There are two things that are obviously wrong:
You do not need variable i, because one of the dimensions is fixed, and you "unrolled" the loop five times
You swapped the indexes: j should go first, that's the one changing from 0 to 9.
For example:
String [] temp=input.split(",");
covar[j][0] = new Double(temp[0]);
covar[j][1] =new Double(temp[1]);
covar[j][2] =new Double(temp[2]);
covar[j][3] =new Double(temp[3]);
covar[j][4] =new Double(temp[4]);
You could put the loop back to shorten your code:
String [] temp=input.split(",");
for (int i = 0 ; i != 5 ; i++) {
covar[j][i] = new Double(temp[i]);
}
It looks like you are using the wrong indicies for you matrix, I think it should be something like this:
int i = 0;
while((input=br.readLine())!= null) {
String [] temp=input.split(",");
//System.out.println(input.split(",").length);
covar[i][0]= new Double(temp[0]);
covar[i][1]=new Double(temp[1]);
covar[i][2]=new Double(temp[2]);
covar[i][3]=new Double(temp[3]);
covar[i][4]=new Double(temp[4]);
++i;
}
Your file might have some strange line-terminators that are making the reader think there is an extra line.
You can try to just make your code skip blank lines:
while((input=br.readLine())!= null) {
if( input.length() > 0 ){
String [] temp=input.split(",");
for (int i = 0 ; i != 5 ; i++) {
covar[j][i] = new Double(temp[i]);
}
}
++j;
}
Related
For now in my program i am using hard-coded values, but i want it so that the user can use any text file and get the same result.
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.File;
public class a1_12177903
{
public static void main(String [] args) throws IOException
{
if (args[0] == null)
{
System.out.println("File not found");
}
else
{
File file = new File(args[0]);
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line = "";
while (br.ready())
{
line += br.readLine();
}
String[] work = line.split(",");
double[] doubleArr = new double[work.length];
for (int i =0; i < doubleArr.length; i++)
{
doubleArr[i] = Double.parseDouble(work[i]);
}
double maxStartIndex=0;
double maxEndIndex=0;
double maxSum = 0;
double total = 0;
double maxStartIndexUntilNow = 0;
for (int currentIndex = 0; currentIndex < doubleArr.length; currentIndex++)
{
double eachArrayItem = doubleArr[currentIndex];
total += eachArrayItem;
if(total > maxSum)
{
maxSum = total;
maxStartIndex = maxStartIndexUntilNow;
maxEndIndex = currentIndex;
}
if (total < 0)
{
maxStartIndexUntilNow = currentIndex;
total = 0;
}
}
System.out.println("Max sum : "+ maxSum);
System.out.println("Max start index : "+ maxStartIndex);
System.out.println("Max end index : " +maxEndIndex);
}
}
}
I've fixed it so it takes in the name of the text file from the command line. if anyone has any ways to improve this, I'll happily accept any improvments.
You can do this with Java8 Streams, assuming each entry has it's own line
double[] doubleArr = Files.lines(pathToFile)
.mapToDouble(Double::valueOf)
.toArray();
If you were using this on production systems (rather than as an exercise) it would be worth while to create the Stream inside a Try with Resources block. This will make sure your input file is closed properly.
try(Stream<String> lines = Files.lines(path)){
doubleArr = stream.mapToDouble(Double::valueOf)
.toArray();
}
If you have a comma separated list, you will need to split them first and use a flatMap.
double[] doubleArr = Files.lines(pathToFile)
.flatMap(line->Stream.of(line.split(","))
.mapToDouble(Double::valueOf)
.toArray();
public static void main(String[] args) throws IOException {
String fileName = "";
File inputFile = new File(fileName);
BufferedReader br = new BufferedReader(new FileReader(inputFile));
// if input is in single line
StringTokenizer str = new StringTokenizer(br.readLine());
double[] intArr = new double[str.countTokens()];
for (int i = 0; i < str.countTokens(); i++) {
intArr[i] = Double.parseDouble(str.nextToken());
}
// if multiple lines in input file for a single case
String line = "";
ArrayList<Double> arryList = new ArrayList<>();
while ((line = br.readLine()) != null) {
// delimiter of your choice
for (String x : line.split(" ")) {
arryList.add(Double.parseDouble(x));
}
}
// convert arraylist to array or maybe process arrayList
}
This link may help: How to use BufferedReader. Then you will get a String containing the array.
Next you have several ways to analyze the string into an array.
Use JSONArray to parse it. For further information, search google for JSON.
Use the function split() to parse string to array. See below.
Code for way 2:
String line="10,20,50";//in fact you get this from file input.
String[] raw=line.split(",");
String[] arr=new String[raw.length];
for(int i=0;i<raw.length;++i)arr[i]=raw[i];
//now arr is what you want
Use streams if you are on JDK8. And please take care of design principles/patterns as well. It seems like a strategy/template design pattern can be applied here. I know, nobody here would ask you to focus on design guidelines.And also please take care of naming conventions. "File" as class name is not a good name.
I have three programs to write for my Object Oriented Programming course, all involving file input/output, each of which contain no compile errors, yet they do not do what they are supposed to in run time (they don't print to the outFile like they're supposed to).
I know that the input file is being read and saved in the correct location, because Eclipse would indicate if either of these was not the case.
Furthermore, I have not (to my knowledge) committed any of the common errors involving not including throws exceptions of closing the read/write files.
I am attaching the first of my i/o assignments here with the hopes that the other files have similar errors that I can fix as soon as I can figure out what's wrong with this one.
import java.io.*;
public class GreenK4_Lab8 {
public static void main(String[] args) throws IOException {
int[] numbers = new int[countLines()];
int i = 0;
for(i = 0; i < numbers.length; i++) {
numbers[i] = readValues(i);
}
printOdd(numbers);
}
public static int countLines() throws IOException {
BufferedReader inFile = new BufferedReader(
new FileReader( "Lab8_TestFile.txt" ) );
int lineNumber = 1;
String nextLine = inFile.readLine();
while( nextLine != null ) {
lineNumber ++;
}
inFile.close();
return lineNumber;
}
public static int readValues(int number) throws IOException {
BufferedReader inFile = new BufferedReader(
new FileReader( "Lab8_TestFile.txt" ) );
int value = 0;
for(int i = 0; i < number; i++) {
String nextLine = inFile.readLine();
value = Integer.parseInt( nextLine );
}
inFile.close();
return value;
}
public static void printOdd(int[] array) throws IOException {
PrintWriter outFile = new PrintWriter( "results.out" );
for(int i = 0; i < array.length; i++) {
int value = array[i];
if( value % 2 != 0)
outFile.println( value );
}
outFile.close();
}
}
The following are the contents of the Lab8_TestFile.txt
4
6
2
10
8
1
-1
-2147483648
2147483647
5
9
3
7
-7
As other commenters pointed out, change your code in countLines function from
String nextLine = inFile.readLine();
while( nextLine != null ) {
lineNumber ++;
}
to
while (inFile.readLine() != null) {
lineNumber ++;
}
With this change your program works as expected.
There are multiple things wrong with your code. Let´s start from the beginning: your countLines method does not work as intended and will create a infinite loop because your while-condition will never be evaluated to false (unless your file is empty):
// String nextLine = inFile.readLine();
// while(nextLine != null) {
while (inFile.readLine() != null) {
lineNumber++;
}
You may want to check Number of lines in a file in Java for a faster and better performing version of retrieving the line count of a file.
Additionally your readValues function opens the file for every line it wants to read, reads the file until that line and closes the file again -> BAD. What you should do instead is the following:
public static void readValues(int[] contentsOfFile) throws IOException {
BufferedReader inFile = new BufferedReader(new FileReader("Lab8_TestFile.txt"));
for(int i = 0; i < contentsOfFile.length; i++) {
String nextLine = inFile.readLine();
contentsOfFile[i] = Integer.parseInt( nextLine );
}
inFile.close();
}
However that is not pretty as well since you rely on a adequately sized int array to be passed in. If you still want to get the line count separately from reading the values, do so, but let the readValues handle the appropriate reading by itself. That could result in something like:
public static ArrayList<Integer> readValues() throws IOException {
BufferedReader inFile = new BufferedReader(new FileReader("Lab8_TestFile.txt"));
ArrayList<Integer> integerContents = new ArrayList<>();
String nextLine = null;
while ((nextLine = inFile.readLine()) != null) {
integerContents.add(Integer.parseInt(nextLine));
}
inFile.close();
return integerContents;
}
That way you parse the file only once for reading the values. If you need to get a int[] back, take a look at How to convert an ArrayList containing Integers to primitive int array? to get an idea on how to extract that from the given data structure.
Your main function might result in something like:
public static void main(String[] args) throws IOException {
int numberOfLines = countLines(); // technically no longer needed.
int[] intContents = convertIntegers(readValues());
printOdd(intContents);
}
I want to sequentially read each line of an input unsorted file into consecutive elements of the array until there are no more records in
the file or until the input size is reached, whichever occurs first. but i can't think of a way to check the next line if its the end of the file?
This is my code:
Scanner cin = new Scanner(System.in);
System.out.print("Max number of items: ");
int max = cin.nextInt();
String[] input = new String[max];
try {
BufferedReader br = new BufferedReader(new FileReader("src/ioc.txt"));
for(int i=0; i<max; i++){ //to do:check for empty record
input[i] = br.readLine();
}
}
catch (IOException e){
System.out.print(e.getMessage());
}
for(int i=0; i<input.length; i++){
System.out.println((i+1)+" "+input[i]);
}
the file has 205 lines, if I input 210 as max, the array prints with five null elements like so..
..204 Seychelles
205 Algeria
206 null
207 null
208 null
209 null
210 null
Thanks for your responses in advance!
From the docs:
public String readLine()
Returns: A String containing the contents of the line, not including
any line-termination characters, or null if the end of the stream has
been reached
In other words, you should do
String aux = br.readLine();
if(aux == null)
break;
input.add(aux)
I recomend you use a variable-size array (you can pre-allocated with the requested size if reasonable). Such that you get either the expected size or the actual number of lines, and can check later.
(depending on how long your file is, you might want to look at readAllLines() too.)
Please refer this Number of lines in a file in Java and modify your for loop to take whatever is the least out of the entered max value or the no.of lines in the file.
Use List<String>
List<String> lines = new ArrayList<>(); // Growing array.
try (BufferedReader br = new BufferedReader(new FileReader("src/ioc.txt"))) {
for(;;) {
String line = br.readLine();
if (line == null) {
break;
}
lines.add(line);
}
} catch (IOException e) {
System.out.print(e.getMessage());
} // Closes automatically.
// If lines wanted as array:
String[] input = lines.toArray(new String[lines.size()]);
Using a dynamically growing ArrayList is the normal way to deal with such problem.
P.S.
FileReader will read in the current platform encoding, i.e. a local file, created locally.
You could do a null check in your first for-loop like:
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
System.out.print("Max number of items: ");
int max = cin.nextInt();
BufferedReader br = new BufferedReader(new FileReader("src/ioc.txt"));
List<String> input = new ArrayList<>();
String nextString;
int i;
for (i = 0; i < max && ((nextString = br.readline()) != null); i++) {
input.add(nextString);
}
for (int j = 0; j < i; j++) {
System.out.println((j + 1) + " " + input.get(j));
}
}
Try :
for(int i=0; i<max; i++){ //to do:check for empty record
if(br.readLine()!=null)
input[i] = br.readLine();
else
break;
}
int i=0;
for(; i<max; i++){ //to do:check for empty record
String line=br.readLine();
if(line==null){
break;
}
input[i] = line;
}
//i will contain the count of lines read. indexes 0...(i-1) represent the data.
I am trying to practice reading text from a file in java. I am little stuck on how I can read N amount of lines, say the first 10 lines in a file and then add the lines in an ArrayList.
Say for example, the file contains 1-100 numbers, like so;
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- ....
I want to read the first 5 numbers, so 1,2,3,4,5 and add it to an array list. So far, this is what I have managed to do but I am stuck and have no clue what to do now.
ArrayList<Double> array = new ArrayList<Double>();
InputStream list = new BufferedInputStream(new FileInputStream("numbers.txt"));
for (double i = 0; i <= 5; ++i) {
// I know I need to add something here so the for loop read through
// the file but I have no idea how I can do this
array.add(i); // This is saying read 1 line and add it to arraylist,
// then read read second and so on
}
You could try using a Scanner and a counter:
ArrayList<Double> array = new ArrayList<Double>();
Scanner input = new Scanner(new File("numbers.txt"));
int counter = 0;
while(input.hasNextLine() && counter < 10)
{
array.add(Double.parseDouble(input.nextLine()));
counter++;
}
This should loop through 10 lines adding each to the arraylist as long as there is more inputs in the file.
See this How to read a large text file line by line using Java?
I think this will work:
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
int i = 0;
while ((line = br.readLine()) != null)
{
if (i < 5)
{
// process the line.
i++;
}
}
br.close();
ArrayList<String> array = new ArrayList<String>();
//ArrayList of String (because you will read strings)
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("numbers.txt")); //to read the file
} catch (FileNotFoundException ex) { //file numbers.txt does not exists
System.err.println(ex.toString());
//here you should stop your program, or find another way to open some file
}
String line; //to store a read line
int N = 5; //max number of lines to read
int counter = 0; //current number of lines already read
try {
//read line by line with the readLine() method
while ((line = reader.readLine()) != null && counter < N) {
//check also the counter if it is smaller then desired amount of lines to read
array.add(line); //add the line to the ArrayList of strings
counter++; //update the counter of the read lines (increment by one)
}
//the while loop will exit if:
// there is no more line to read (i.e. line==null, i.e. N>#lines in the file)
// OR the desired amount of line was correctly read
reader.close(); //close the reader and related streams
} catch (IOException ex) { //if there is some input/output problem
System.err.println(ex.toString());
}
List<Integer> array = new ArrayList<>();
try (BufferedReader in = new BufferedReader(
new InputStreamReader(new FileInputStream("numbers.txt")))) {
for (int i = 0; i < 5; ++i) { // Loops 5 times
String line = in.readLine();
if (line == null) [ // End of file?
break;
}
// line does not contain line-ending.
int num = Integer.parseInt(line);
array.add(i);
}
} // Closes in.
System.out.println(array);
You can do this with:
try (BufferedReader reader = Files.newBufferedReader(Paths.get("numbers.txt"))) {
List<String> first10Numbers = reader.lines().limit(10).collect(Collectors.toList());
// do something with the list here
}
As complete example as JUnit test:
public class ReadFirstLinesOfFileTest {
#Test
public void shouldReadFirstTenNumbers() throws Exception {
Path p = Paths.get("numbers.txt");
Files.write(p, "0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n".getBytes());
try (BufferedReader reader = Files.newBufferedReader(Paths.get("numbers.txt"))) {
List<String> first10Numbers = reader.lines().limit(10).collect(Collectors.toList());
List<String> expected = Arrays.asList("0", "1", "2", "3", "4", "5", "6", "7", "8", "9");
Assert.assertArrayEquals(expected.toArray(), first10Numbers.toArray());
}
}
}
ArrayList<Double> myList = new ArrayList<Double>();
int numberOfLinesToRead = 5;
File f = new File("number.txt");
Scanner fileScanner = new Scanner(f);
for(int i=0; i<numberOfLinesToRead; i++){
myList.add(fileScanner.nextDouble());
}
Make sure you have "numberOfLinesToRead" lines in your file.
BufferedReader br = new BufferedReader(new FileReader(file));
List<String> nlines = IntStream.range(0, hlines)
.mapToObj(i -> readLine(br)).collect(Collectors.toList());
String readLine(BufferedReader reader) {
try {
return reader.readLine();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I compare strings in Java?
Consider the following 2D array of Strings a[5][5],
I store three values in the first three blocks in the array "a".
When I print my array, I get the following output.
ABC
null
DEF
null
These values are present in a file and I retrieve the values and store them in an array of strings.
The file ("file.txt")looks like this,
A B C
D E F
Here is my code,
Declaration:
static String [][] a= new String [4][4];
public static String newline = System.getProperty("line.separator");
private static int i,j;
Main code:
i=j=0;
FileInputStream fin;
fin = new FileInputStream("file.txt");
DataInputStream in = new DataInputStream (fin);
BufferedReader br = new BufferedReader (new InputStreamReader (in));
while((c = (char)br.read()) != (char)-1)
{
if (c != ' ' && c != (char)'\n')
{
a[i][j] = Character.toString(c);
j++;
}
else if (c == '\n')
{
i++;
j = 0;
}
}
for (int i=0;i<5;i++)
{
for (int j=0;j<5;j++)
{
if (newline.equals(a[i][j]))
{
mainArray[i][j] = null;
}
}
}
Here is how I print my array,
for (int i=0;i<5;i++)
{
for (int j=0;j<5;j++)
{
System.out.print(a[i][j]);
}
System.out.println("");
}
My desired output should be,
ABCnullnull
DEFnullnull
Is there a better way to work on this problem??
BufferedReader has a readLine() method that will return a string with all the chars preceding the \n or \r. It also returns null at the end of the stream.
FileInputStream fin;
fin = new FileInputStream("file.txt");
DataInputStream in = new DataInputStream (fin);
BufferedReader br = new BufferedReader (new InputStreamReader (in));
List<String> list = new ArrayList<String>();
String line;
while ((line= br.readLine())!=null)
{
list.add(line);
}
This will cope with any number of returns and arbitrary length strings.
Or if you must have each line as and array
FileInputStream fin;
fin = new FileInputStream("file.txt");
DataInputStream in = new DataInputStream(fin);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
List<char[]> list = new ArrayList<char[]>();
String line;
while ((line = br.readLine()) != null) {
if(!line.isEmpty()) list.add(line.toCharArray());
}
Reading your file should result in a List size of two each containing and array of 5 chars. ['A',' ','B',' ','C'] then ['D',' ','E',' ','F']
Try
public static String newline = System.getProperty("line.separator");
for (int i=0;i<5;i++)
{
if (newline.equals(a[i]))
{
a[i] = null;
}
}
EDITED ANSWER:
From reading your responses and looking at what your expected output is, you may be better off doing something like this...
pseudo-code
read entire line into String array index
Before printing, check length of String (a[i].length)
If length is less than 5, add 'null' to the end of the String for every character less than 5
Thus:
if(a[i].length < 5)
{
int index = 5 - a[i].length;
for( ; index > 0; index --)
{
a[i].concat("null");
}
}
ORIGINAL ANSWER............
Not sure if my comment was sent to you or not. You might just be indexing too far out.
Try
for(int i = 0; i < 4; i++)
System.print(a[i]);