Code for reading from a text file doesn't work - java

I am new to Java and it has all been self-taught. I enjoy working with the code and it is just a hobby, so, I don't have any formal education on the topic.
I am at the point now where I am learning to read from a text file. The code that I have been given isn't correct. It works when I hardcode the exact number of lines but if I use a "for" loop to sense how many lines, it doesn't work.
I have altered it a bit from what I was given. Here is where I am now:
This is my main class
package textfiles;
import java.io.IOException;
public class FileData {
public static void main(String[] args) throws IOException {
String file_name = "C:/Users/Desktop/test.txt";
ReadFile file = new ReadFile(file_name);
String[] aryLines = file.OpenFile();
int nLines = file.readLines();
int i = 0;
for (i = 0; i < nLines; i++) {
System.out.println(aryLines[i]);
}
}
}
This is my class that will read the text file and sense the number of lines
package textfiles;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFile {
private String path;
public ReadFile(String file_path) {
path = file_path;
}
int readLines() throws IOException {
FileReader file_to_read = new FileReader(path);
BufferedReader bf = new BufferedReader(file_to_read);
int numberOfLines = 0;
String aLine;
while ((aLine = bf.readLine()) != null) {
numberOfLines++;
}
bf.close();
return numberOfLines;
}
public String[] OpenFile() throws IOException {
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
int numberOfLines = 0;
String[] textData = new String[numberOfLines];
int i;
for (i = 0; i < numberOfLines; i++) {
textData[i] = textReader.readLine();
}
textReader.close();
return textData;
}
}
Please, keep in mind that I am self-taught; I may not indent correctly or I may make simple mistakes but don't be rude. Can someone look this over and see why it is not sensing the number of lines (int numberOfLines) and why it won't work unless I hardcode the number of lines in the readLines() method.

The problem is, you set the number of lines to read as zero with int numberOfLines = 0;
I'd rather suggest to use a list for the lines, and then convert it to an array.
public String[] OpenFile() throws IOException {
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
//int numberOfLines = 0; //this is not needed
List<String> textData = new ArrayList<String>(); //we don't know how many lines are there going to be in the file
//this part should work akin to the readLines part
String aLine;
while ((aLine = bf.readLine()) != null) {
textData.add(aLine); //add the line to the list
}
textReader.close();
return textData.toArray(new String[textData.size()]); //convert it to an array, and return
}
}

int numberOfLines = 0;
String[] textData = new String[numberOfLines];
textData is an empty array. The following for loop wont do anything.
Note also that this is not the best way to read a file line by line. Here is a proper example on how to get the lines from a text file:
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
ArrayList<String> list = new ArrayList<String>();
while ((line = br.readLine()) != null) {
list.add(line);
}
br.close();
I also suggest that you read tutorials on object oriented concepts.

This is a class that I wrote awhile back that I think you may find helpful.
public class FileIO {
static public String getContents(File aFile) {
StringBuilder contents = new StringBuilder();
try {
//use buffering, reading one line at a time
//FileReader always assumes default encoding is OK!
BufferedReader input = new BufferedReader(new FileReader(aFile));
try {
String line = null; //not declared within while loop
/*
* readLine is a bit quirky :
* it returns the content of a line MINUS the newline.
* it returns null only for the END of the stream.
* it returns an empty String if two newlines appear in a row.
*/
while ((line = input.readLine()) != null) {
contents.append(line);
contents.append(System.getProperty("line.separator"));
}
} finally {
input.close();
}
} catch (IOException ex) {
}
return contents.toString();
}
static public File OpenFile()
{
return (FileIO.FileDialog("Open"));
}
static private File FileDialog(String buttonText)
{
String defaultDirectory = System.getProperty("user.dir");
final JFileChooser jfc = new JFileChooser(defaultDirectory);
jfc.setMultiSelectionEnabled(false);
jfc.setApproveButtonText(buttonText);
if (jfc.showOpenDialog(jfc) != JFileChooser.APPROVE_OPTION)
{
return (null);
}
File file = jfc.getSelectedFile();
return (file);
}
}
It is used:
File file = FileIO.OpenFile();
It is designed specifically for reading in files and nothing else, so can hopefully be a useful example to look at in your learning.

Related

Failed to add to tree map that is inside another map (to create an inverted index)

I am working in creating inverted index for list of words in java. Basically it creates a list for each word contains the document index that word appear on associated with frequency of word in that document, the desired output should be like this:
[word1:[FileNo:frequency],[FileNo:frequency],[FileNo:frequency],word2:[FileNo:frequency],[FileNo:frequency]...etc]
Here is the code:
package assigenment2;
import java.io.*;
import java.util.*;
public class invertedIndex {
public static Map<String, Map<Integer,Integer>> wordTodocumentMap;
public static BufferedReader buffer;
public static BufferedReader br;
public static BufferedReader reader;
public static List<String> files = new ArrayList<String>();
public static List<String>[] tokens;
public static void main(String[] args) throws IOException {
//read the token file and store the token in list
String tokensPath="/Users/Manal/Documents/workspace/Information Retrieval/tokens.txt";
int k=0;
String[] tokens = new String[8500];
String sCurrentLine;
try
{
FileReader fr=new FileReader(tokensPath);
BufferedReader br= new BufferedReader(fr);
while ((sCurrentLine = br.readLine()) != null)
{
tokens[k]=sCurrentLine;
k++;
}
System.out.println("the number of token are:"+k+" words");
br.close();
}
catch(Exception ex)
{System.out.println(ex);}
Until there it works correctly, I believe that the problem is in the manipulating the nested map in the following part:
TreeMap<Integer,Integer> documentToCount = new TreeMap<Integer,Integer>();
//read files
System.out.print("Enter the path of files you want to process:\n");
Scanner InputPath = new Scanner(System.in);
String cranfield = InputPath.nextLine();
File cranfieldFiles = new File(cranfield);
for (File file: cranfieldFiles.listFiles())
{
int fileno = files.indexOf(file.getPath());
if (fileno == -1) //the current file isn't in the files list \
{
files.add(file.getPath());// add file to the files list
fileno = files.size() - 1;//the index of file will start from 0 to size-1
}
int frequency = 0;
BufferedReader reader = new BufferedReader(new FileReader(file));
for (String line = reader.readLine(); line != null; line = reader.readLine())
{
for (String _word : line.split(" "))
{
String word = _word.toLowerCase();
if (Arrays.asList(tokens).contains(word))
if (wordTodocumentMap.get(word) == null)//check whether word is new word
{
documentToCount = new TreeMap<Integer,Integer>();
wordTodocumentMap.put(word, documentToCount);
}
documentToCount.put(fileno, frequency+1);//add the location and frequency
}
}
}
reader.close();
}
}
The error I get is:
Exception in thread "main" java.lang.NullPointerException
at assigenment2.invertedIndex.main(invertedIndex.java:65)
You’re never instantiating wordTodocumentMap, so it remains null throughout. Therefore the line if (wordTodocumentMap.get(word) == null)//check whether word is new word throws a NullPointerException when you do .get(), that is, before you have anything to compare to null. One possible solution is to instantiate the map in the declaration:
public static Map<String, Map<Integer,Integer>> wordTodocumentMap = new HashMap<>();
There may be other problems in your code, but this should get you a step further.

Read and write text file with escape sequences

Learning Java by coding...
Read and write text file to insert tabs to further be imported into Mnemosyne
I got a text file written by hand by myself like this:
First line of text\tansewer
Second line of text\tanswer
Third line of text\tansewer
However when I try to print it or write it to a file I don't get the tab I need.
public static void main(String[] args) {
String fileName = "jeg.txt";
String line = null;
String[] mylines = new String[20];
int i = 0;
try {
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
mylines[i++] = line;
}
bufferedReader.close();
}
All you are doing is reading the information into a variable. Once you have the information, you have to output it somewhere for it to show up.
public static void main(String[] args) {
String fileName = "jeg.txt";
String line = null;
String[] mylines = new String[20];
int i = 0;
try {
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
mylines[i++] = line;
}
bufferedReader.close();
}
for(int j=0;j<i;j++){
System.out.println(mylines[j]);
}
This will output your lines to the system line. You can use the same concept in a tab or anywhere else.

Java - File being read returns null

Hi I am loading a file into my program and assigning each value (stored on a new line to a array) I cant seem to spot why the array holding the file content is null in each index.
private void readAndProcessWords() {
try {
FileReader _fr = new FileReader(FILEPATH);
BufferedReader textReader = new BufferedReader(_fr);
int numLines = getNumLines(textReader);
String[] words = new String[numLines];
for(int i=0;i<numLines;i++){
words[i] = textReader.readLine();
System.out.println(words[i]);
}
//clears memory reserved for this buffered reader
textReader.close();
} catch(IOException e) {
System.out.println(e);
}
}
private int getNumLines(BufferedReader textReader) throws IOException{
String line;
int numLines =0;
while((line = textReader.readLine()) != null){
numLines++;
}
return numLines;
}
}
Solution: add the below code above the loop to 'reset' the file reader
_fr = new FileReader(FILEPATH);
textReader = new BufferedReader(_fr);
The easiest solution is to recreate your Reader, the issue is that calling getNumLines() moves the position in your BufferedReader to the end of file.
BufferedReader textReader = new BufferedReader(_fr);
int numLines = getNumLines(textReader); // <-- textReader is at EOF after this.
textReader.close();
textReader = new BufferedReader(_fr);
Instead of reading your file twice to get the line count (which is slow, annoying, and will not work if the file changes between the two calls), read the lines into a variable-sized list:
private void readAndProcessWords() {
try {
FileReader _fr = new FileReader(FILEPATH);
BufferedReader textReader = new BufferedReader(_fr);
List<String> words = new ArrayList<>();
String line;
while ((line = textReader.readLine()) != null) {
words.add(line);
}
textReader.close();
for (String word : words) {
System.out.println(word);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
Good news: this functionality already exists, so you don't need to rewrite it.
private void readAndProcessWords() {
try {
List<String> words = Files.readAllLines(Paths.get(FILEPATH));
for (String word : words) {
System.out.println(word);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
Since a buffered reader is an object you pass it as a reference to the getNumLines() not as a copy, so you end up getting a null when you .readLine() on the same buffered reader you sent to the getNumLines() because you have already run .readLine() to its limit.
After running getNumLines() close and reopen the document with a new buffered reader.
I also remember there being a Mark() and Recall() method for buffered reader in java that could also serve as a work around.
I think like.
FileReader _fr = new FileReader(FILEPATH);
BufferedReader textReader = new BufferedReader(_fr);
textReader.Mark();
int numLines = getNumLines(textReader);
textReader.Recall();
String[] words = new String[numLines];
for(int i=0;i<numLines;i++)
{
words[i] = textReader.readLine();
System.out.println(words[i]);
}
//clears memory reserved for this buffered reader
textReader.close();

Reading a file in Java

I have the following code to open and read a file. I'm having trouble figuring out how I can have it go through and print the total number of each character in the file, print the first and last character, and print the character exactly in the middle of the file. What's the most efficient way to do this?
This is the main class:
import java.io.IOException;
public class fileData {
public static void main(String[ ] args) throws IOException {
String file_name = "/Users/JDB/NetBeansProjects/Program/src/1200.dna";
try {
ReadFile file = new ReadFile(file_name);
String[] arrayLines = file.OpenFile();
int i;
for (i=0; i<arrayLines.length; i++)
{
System.out.println(arrayLines[i]);
}
}
catch (IOException e) {
System.out.println(e.getMessage()) ;
}
}
}
and the other class:
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
public class ReadFile {
private String path;
public ReadFile (String file_path)
{
path = file_path;
}
public String[] OpenFile() throws IOException
{
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
int numberOfLines = readLines();
String[] textData = new String[numberOfLines];
int i;
for(i=0; i<numberOfLines; i++)
{
textData[i] = textReader.readLine();
}
textReader.close();
return textData;
}
int readLines() throws IOException
{
FileReader file_to_read = new FileReader(path);
BufferedReader bf = new BufferedReader(file_to_read);
String aLine;
int numberOfLines = 0;
while (( aLine = bf.readLine() ) != null)
{
numberOfLines++;
}
bf.close();
return numberOfLines;
}
Some hints which might help.
A Map can be used to store information about each character in the alphabet.
The middle of the file can be found from the size of the file.
These few lines of code will do it (using Apache's FileUtils library):
import org.apache.commons.io.FileUtils;
public static void main(String[] args) throws IOException {
String str = FileUtils.readFileToString(new File("myfile.txt"));
System.out.println("First: " + str.charAt(0));
System.out.println("Last: " + str.charAt(str.length() - 1));
System.out.println("Middle: " + str.charAt(str.length() / 2));
}
Anyone who says "you can't use libraries for homework" isn't being fair - in the real world we always use libraries in preference to reinventing the wheel.
The easiest way to understand I can think of is to read the entire file in as a String. Then use the methods on the String class to get the first, last, and middle character (character at index str.length()/2).
Since you are already reading in the file a line at a time, you can use a StringBuilder to construct a string out of those lines. Using the resulting String, the charAt() and substring() methods you should be able to get out everything you want.

Java file read problem

I have a java problem. I am trying to read a txt file which has a variable number of integers per line, and for each line I need to sum every second integer! I am using scanner to read integers, but can't work out when a line is done. Can anyone help pls?
have a look at the BufferedReader class for reading a textfile and at the StringTokenizer class for splitting each line into strings.
String input;
BufferedReader br = new BufferedReader(new FileReader("foo.txt"));
while ((input = br.readLine()) != null) {
input = input.trim();
StringTokenizer str = new StringTokenizer(input);
String text = str.nextToken(); //get your integers from this string
}
If I were you, I'd probably use FileUtils class from Apache Commons IO. The method readLines(File file) returns a List of Strings, one for each line. Then you can simply handle one line at a time.
Something like this:
File file = new File("test.txt");
List<String> lines = FileUtils.readLines(file);
for (String line : lines) {
// handle one line
}
(Unfortunately Commons IO doesn't support generics, so the there would be an unchecked assignment warning when assigning to List<String>. To remedy that use either #SuppressWarnings, or just an untyped List and casting to Strings.)
This is, perhaps, an example of a situation where one can apply "know and use the libraries" and skip writing some lower-level boilerplate code altogether.
or scrape from commons the essentials to both learn good technique and skip the jar:
import java.io.*;
import java.util.*;
class Test
{
public static void main(final String[] args)
{
File file = new File("Test.java");
BufferedReader buffreader = null;
String line = "";
ArrayList<String> list = new ArrayList<String>();
try
{
buffreader = new BufferedReader( new FileReader(file) );
line = buffreader.readLine();
while (line != null)
{
line = buffreader.readLine();
//do something with line or:
list.add(line);
}
} catch (IOException ioe)
{
// ignore
} finally
{
try
{
if (buffreader != null)
{
buffreader.close();
}
} catch (IOException ioe)
{
// ignore
}
}
//do something with list
for (String text : list)
{
// handle one line
System.out.println(text);
}
}
}
This is the solution that I would use.
import java.util.ArrayList;
import java.util.Scanner;
public class Solution1 {
public static void main(String[] args) throws IOException{
String nameFile;
File file;
Scanner keyboard = new Scanner(System.in);
int total = 0;
System.out.println("What is the name of the file");
nameFile = keyboard.nextLine();
file = new File(nameFile);
if(!file.exists()){
System.out.println("File does not exit");
System.exit(0);
}
Scanner reader = new Scanner(file);
while(reader.hasNext()){
String fileData = reader.nextLine();
for(int i = 0; i < fileData.length(); i++){
if(Character.isDigit(fileData.charAt(i))){
total = total + Integer.parseInt(fileData.charAt(i)+"");
}
}
System.out.println(total + " \n");
}
}
}

Categories

Resources