Buffered text writer to file - java

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.

Related

Why is my program reading one less line than there actually is? And why is my array taking in only ones?

In my high school comp sci class I have to read a text file with marks and then create an array with those marks in them (so I can manipulate them later). When I try and read the number of lines in the program it reads one less than there is, and when I output the array it consists of only "1.00" written to the amount of lines it has counted (which is incorrect).
import java.awt.*;
import java.io.*;
import hsa.Console;
public class Assignment3Q3
{
static Console c;
public static void main (String[] args) throws IOException
{
c = new Console ();
BufferedReader input = new BufferedReader (new FileReader ("marks.txt"));
String mark = input.readLine ();
int lines = 0;
while (input.readLine () != null)
lines++;
input.close ();
c.println (lines);
double[] marks = new double [lines];
int count = 0;
BufferedReader input1 = new BufferedReader (new FileReader ("marks.txt"));
while (input1.readLine () != null)
{
marks [count] = Double.parseDouble (mark);
count += 1;
if (count == lines)
{
break;
}
}
for (int x = 0 ; x < lines ; x++)
{
c.println (marks [x]);
}
}
}
In your second while loop, you are always assigning the parsed version of mark variable to the marks array elements. But you have only set mark variable once in your code, which is the first line of your file.
Anyway without reading the file twice (once to get the number of lines and then to store the actual line content), you can do this in a single read cycle by using a List instead of an array.
try (BufferedReader input = new BufferedReader (new FileReader("src/marks.txt"))) {
List<Double> marks = new ArrayList<>();
String line;
while ((line = input.readLine()) != null) {
marks.add(Double.parseDouble(line));
}
System.out.println(marks);
} catch (IOException e) {
e.printStackTrace();
}
In case you really want to get these marks to an array, you can onvert the above list into an array as follows.
Double[] marksArray = marks.toArray(new Double[marks.size()]);
Also as I have done in the above code snippet, better to use try with resources approach when you create AutoCloseable resources such as BufferedReader or FileReader. Then you don't have to close them explicitly in your code.
Why this separation in two steps at all? This is error prone. No values in the marks-array above the current line-count are accessed. So store the doubles in a dynamicly growing ArrayList<Double> instead and do the job in one step.

Read txt and save into array,java

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.

Read a definite number of lines in a text file, using java

I have a text file with data. The file has information from all months. Imagine that the information for January occupy 50 lines. Than February starts and it occupies 40 more lines. Than I have March and so on... Is it possible to read only part of the file? Can I say "read from line X to line Y"? or is there a better way to accomplish this? I only want to print the data correspondent to one month not the all file. Here is my code
public static void readFile()
{
try
{
DataInputStream inputStream =
new DataInputStream(new FileInputStream("SpreadsheetDatabase2013.txt"));
while(inputStream.available() != 0)
{
System.out.println("AVAILABLE: " + inputStream.available());
System.out.println(inputStream.readUTF());
System.out.println(inputStream.readInt());
for (int i = 0; i < 40; i++)
{
System.out.println(inputStream.readUTF());
System.out.println(inputStream.readUTF());
System.out.println(inputStream.readUTF());
System.out.println(inputStream.readUTF());
System.out.println(inputStream.readUTF());
System.out.println(inputStream.readDouble());
System.out.println(inputStream.readUTF());
System.out.println(inputStream.readBoolean());
System.out.println();
}
}// end while
inputStream.close();
}// end try
catch (Exception e)
{
System.out.println("An error has occurred.");
}//end catch
}//end method
Thank you for your time.
My approach to this would be to read the entire contents of the text file and store it in a ArrayList and read only the lines for the requested month.
Example:
Use this function to read the all the lines from the file.
/**
* Read from a file specified by the filePath.
*
* #param filePath
* The path of the file.
* #return List of lines in the file.
* #throws IOException
*/
public static ArrayList<String> readFromFile(String filePath)
throws IOException {
ArrayList<String> temp = new ArrayList<String>();
File file = new File(filePath);
if (file.exists()) {
BufferedReader brin;
brin = new BufferedReader(new FileReader(filePath));
String line = brin.readLine();
while (line != null) {
if (!line.equals(""))
temp.add(line);
line = brin.readLine();
}
brin.close();
}
return temp;
}
Then read only the ones you need from ArrayList temp.
Example:
if you want to read February month's data assuming its 50 lines of data and starts from 40th line.
for(int i=40;i<90;i++)
{
System.out.println(temp.get(i));
}
Note: This is only just one way of doing this. I am not certain if there is any other way!
I would use the scanner class.
Scanner scanner = new Scanner(filename);
Use scanner.nextLine() to get each of the lines of the file. If you only want from line x to line y you can use a for loop to scan each of the lines that you don't need before going through the scanner for the lines you do need. Be careful not to hit an exception without throwing it though.
Or you can go through the scanner and for each line, add the String contents of the line to an ArrayList. Good luck.
Based on how you said your data was organized, I would suggest doing something like this
ArrayList<String> temp = new ArrayList<String>();
int read = 0;
File file = new File(filePath);
if (file.exists()) {
BufferedReader brin;
brin = new BufferedReader(new FileReader(filePath));
String line = brin.readLine();
while (line != null) {
if (!line.equals("")){
if(line.equals("March"))
read = 1;
else if(line.equals("April"))
break;
else if(read == 1)
temp.add(line);
}
line = brin.readLine();
}
brin.close();
Just tried it myself, that'll take in all the data between March and April. You can adjust them as necessary or make them variables. Thanks to ngoa for the foundation code. Credit where credit is due
If you have Java 7, you can use Files.readAllLines(Path path, Charset cs), e.g.
Path path = // Path to "SpreadsheetDatabase2013.txt"
Charset charset = // "UTF-8" or whatever charset is used
List<String> allLines = Files.readAllLines(path, charset);
List<String> relevantLines = allLines.subList(x, y);
Where x (inclusive) and y (exclusive) indicates the line numbers that are of interest, see List.subList(int fromIndex, int toIndex).
One benefit of this solution, as stated in the JavaDoc of readAllLines():
This method ensures that the file is closed when all bytes have been read or an I/O error, or other runtime exception, is thrown.

Print data from file to array

I need to have this file print to an array, not to screen.And yes, I MUST use an array - School Project - I'm very new to java so any help is appreciated. Any ideas? thanks
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class HangmanProject
{
public static void main(String[] args) throws FileNotFoundException
{
String scoreKeeper; // to keep track of score
int guessesLeft; // to keep track of guesses remaining
String wordList[]; // array to store words
Scanner keyboard = new Scanner(System.in); // to read user's input
System.out.println("Welcome to Hangman Project!");
// Create a scanner to read the secret words file
Scanner wordScan = null;
try {
wordScan = new Scanner(new BufferedReader(new FileReader("words.txt")));
while (wordScan.hasNext()) {
System.out.println(wordScan.next());
}
} finally {
if (wordScan != null) {
wordScan.close();
}
}
}
}
Nick, you just gave us the final piece of the puzzle. If you know the number of lines you will be reading, you can simply define an array of that length before you read the file
Something like...
String[] wordArray = new String[10];
int index = 0;
String word = null; // word to be read from file...
// Use buffered reader to read each line...
wordArray[index] = word;
index++;
Now that example's not going to mean much to be honest, so I did these two examples
The first one uses the concept suggested by Alex, which allows you to read an unknown number of lines from the file.
The only trip up is if the lines are separated by more the one line feed (ie there is a extra line between words)
public static void readUnknownWords() {
// Reference to the words file
File words = new File("Words.txt");
// Use a StringBuilder to buffer the content as it's read from the file
StringBuilder sb = new StringBuilder(128);
BufferedReader reader = null;
try {
// Create the reader. A File reader would be just as fine in this
// example, but hay ;)
reader = new BufferedReader(new FileReader(words));
// The read buffer to use to read data into
char[] buffer = new char[1024];
int bytesRead = -1;
// Read the file to we get to the end
while ((bytesRead = reader.read(buffer)) != -1) {
// Append the results to the string builder
sb.append(buffer, 0, bytesRead);
}
// Split the string builder into individal words by the line break
String[] wordArray = sb.toString().split("\n");
System.out.println("Read " + wordArray.length + " words");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception e) {
}
}
}
The second demonstrates how to read the words into an array of known length. This is probably closer to the what you actually want
public static void readKnownWords()
// This is just the same as the previous example, except we
// know in advance the number of lines we will be reading
File words = new File("Words.txt");
BufferedReader reader = null;
try {
// Create the word array of a known quantity
// The quantity value could be defined as a constant
// ie public static final int WORD_COUNT = 10;
String[] wordArray = new String[10];
reader = new BufferedReader(new FileReader(words));
// Instead of reading to a char buffer, we are
// going to take the easy route and read each line
// straight into a String
String text = null;
// The current array index
int index = 0;
// Read the file till we reach the end
// ps- my file had lots more words, so I put a limit
// in the loop to prevent index out of bounds exceptions
while ((text = reader.readLine()) != null && index < 10) {
wordArray[index] = text;
index++;
}
System.out.println("Read " + wordArray.length + " words");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception e) {
}
}
}
If you find either of these useful, I would appropriate it you would give me a small up-vote and check Alex's answer as correct, as it's his idea that I've adapted.
Now, if you're really paranoid about which line break to use, you can find the values used by the system via the System.getProperties().getProperty("line.separator") value.
Do you need more help with the reading the file, or getting the String to a parsed array? If you can read the file into a String, simply do:
String[] words = readString.split("\n");
That will split the string at each line break, so assuming this is your text file:
Word1
Word2
Word3
words will be: {word1, word2, word3}
If the words you are reading are stored in each line of the file, you can use the hasNextLine() and nextLine() to read the text one line at a time. Using the next() will also work, since you just need to throw one word in the array, but nextLine() is usually always preferred.
As for only using an array, you have two options:
You either declare a large array, the size of whom you are sure will never be less than the total amount of words;
You go through the file twice, the first time you read the amount of elements, then you initialize the array depending on that value and then, go through it a second time while adding the string as you go by.
It is usually recommended to use a dynamic collection such as an ArrayList(). You can then use the toArray() method to turnt he list into an array.

Read input as array

I want to make something read from inputstream to store in an int[] when I type "read 1 2 3 4". what should i do?
I do not know the size of the array, everything is dynamic...
Here is the current code:
BufferedReader stdin = new BufferedReader(
new InputStreamReader(System.in));
String line = stdin.readLine();
StringTokenizer st = new StringTokenizer(line);
String command = st.nextToken();
if (command.equals("read")) {
while (st.nextToken() != null) {
//my problem is no sure the array size
}
}
You need to build something to parse the input stream. Assuming it's literally as uncomplex as you've indicated the first thing you need to do is get the line out of the InputStream, you can do that like this:
// InputStream in = ...;
// read and accrue characters until the linebreak
StringBuilder sb = new StringBuilder();
int c;
while((c = in.read()) != -1 && c != '\n'){
sb.append(c);
}
String line = sb.toString();
Or you can use a BufferedReader (as suggested by comments):
BufferedReader rdr = new BufferedReader(new InputStreamReader(in));
String line = rdr.readLine();
Once you have a line to process you need to split it into pieces, then process the pieces into the desired array:
// now process the whole input
String[] parts = line.split("\\s");
// only if the direction is to read the input
if("read".equals(parts[0])){
// create an array to hold the ints
// note that we dynamically size the array based on the
// the length of `parts`, which contains an array of the form
// ["read", "1", "2", "3", ...], so it has size 1 more than required
// to hold the integers, thus, we create a new array of
// same size as `parts`, less 1.
int[] inputInts = new int[parts.length-1];
// iterate through the string pieces we have
for(int i = 1; i < parts.length; i++){
// and convert them to integers.
inputInts[i-1] = Integer.parseInt(parts[i]);
}
}
I'm sure some of these methods can throw exceptions (at least read and parseInt do), I'll leave handling those as an exercise.
You either use a storing structure with nodes, that you can easily append one after another, or, if you really must use arrays, you need to allocate space periodically, as it becomes necessary.
Parse-out the data and keyword from your string then push it into something like this:
public static Integer[] StringToIntVec( String aValue )
{
ArrayList<Integer> aTransit = new ArrayList<Integer>();
for ( String aString : aValue.split( "\\ ") )
{
aTransit.add( Integer.parseInt( aString ) );
}
return aTransit.toArray( new Integer[ 0 ] );
}

Categories

Resources