Hey so I've written some code to read the contents of a text file, do some comparisons and output either 1 or 0 into a 2D array. Here is a snippet
import java.io.*;
import java.util.*;
public class readFile
{
private String path;
//declare variables for visited and link
//String inputSearch1 = "Visited";
//String inputSearch2 = "Link";
String word;
public readFile(String pathname)
{
path = pathname;
}
//open the file and read it and search each line of the file for 'Visited' and 'Link'
public String[] OpenFile() throws IOException
{
FileReader fr = new FileReader(path);
BufferedReader lineReader = new BufferedReader(fr);
int numberOfLines = readLines();
String[] lineData = new String[numberOfLines];
int i;
for(i=0; i<numberOfLines; i++)
{
lineData[i] = lineReader.readLine();
}
lineReader.close();
return lineData;
}
//allows the file to be parsed without knowing the exact number of lines in it
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;
}
int outLinks;
int inLinks;
String bLine;
String[] searchStrings() throws IOException
{
FileReader ftr = new FileReader(path);
BufferedReader bf2 = new BufferedReader(ftr);
int numberOfLines = readLines();
//String bLine;
String[] parseLine = new String[numberOfLines]; //array to store lines of text file
int[][] linkMatrix = new int[outLinks][inLinks]; //2d array to store the outLinks and inLinks
int i;
for(i=0; i<numberOfLines; i++)
{
parseLine[i] = bf2.readLine();
int j, k;
for(j=0; j<outLinks; j++)
{
for(k=0; k<inLinks;k++)
{
if(bLine.startsWith("Visited") && equals(bLine.startsWith("Link")))
{
linkMatrix[outLinks][inLinks] = 1;
}
else
{
linkMatrix[outLinks][inLinks] = 0;
}System.out.println(Arrays.deepToString(linkMatrix));
}//System.out.println();
}
}bf2.close();
return parseLine;
}
I am now trying to output this from the main method but each time I run it, all I get is the contents of the text file and no 2D matrix.
import java.io.IOException;
public class linkStatistics
{
public static void main(String[] args) throws IOException
{
// TODO Auto-generated method stub
//read file
String fileName = "C:\\Users\\Ikemesit\\Documents\\Lab_4.txt";
try
{
readFile file = new readFile(fileName);
//String[] lines = file.OpenFile();
String[] lines = file.searchStrings();
int i;
for(i=0;i<lines.length;i++)
{
System.out.println(lines[i]);
//System.out.println(lines2[i]);
}
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
}
}
Any help would be much appreciated! Thanks.
This condition has many problems :
if(bLine.startsWith("Visited") && equals(bLine.startsWith("Link")))
You never initialize bLine. This means that the condition would throws NullPointerException. I'm assuming you want to test the lines you read from the file instead.
equals makes no sense in this context - it compares your readFile instance with a boolean.
A line can't start with both prefixes, so you probably want || (OR) instead of && (AND).
I think this would make more sense :
if(parseLine[i].startsWith("Visited") || parseLine[i].startsWith("Link"))
Related
I am trying to use the return value fileName from the method file(), to the method nGram() so I can parse the contents of the file into n-grams. I have working code to do this but I want have two seperate methods.
package ie.gmit.sw;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Example {
private String fileName;
private int k;
public Example(String fileName, int k) {
this.fileName = fileName;
this.k = k;
}
public String file(String fileName) throws IOException {
//Open the file.
FileReader fr = new FileReader(fileName);
Scanner inFile = new Scanner(fr);
// Read lines from the file till end of file
while (inFile.hasNext()) {
// Read the next line.
String line = inFile.nextLine();
// Display the line.
System.out.println(line);
}
// Close the file.
inFile.close();
return fileName;
}
private void nGram() throws IOException{
List<String> ngrams = new ArrayList<>();
for (int i = 0; i <= fileName.length() - k; i++) {
ngrams.add(fileName.substring(i, i + k));
}
System.out.println(ngrams);
}
//Working
// private static void run() throws FileNotFoundException {
// // Open the file.
// FileReader fr = new FileReader(fileName);
// Scanner inFile = new Scanner(fr);
//
// // Read lines from the file till end of file
// while (inFile.hasNext()) {
// // Read the next line.
// String line = inFile.nextLine();
// // Display the line.
// System.out.println(line);
//
// List<String> ngrams = new ArrayList<>();
// for (int i = 0; i <= line.length() - k; i++) {
// ngrams.add(line.substring(i, i + k));
// }
// System.out.println(ngrams);
// }
//
// // Close the file.
// inFile.close();
// }
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter file: ");
String fileName = scanner.nextLine();
System.out.println("Enter kmers: ");
int k = scanner.nextInt();
scanner.close();
Example e = new Example(fileName, k);
e.file(fileName);
e.nGram();
}
}
Output
Hello world
Good Day okay
random text saying anything me laptop bye
[sa, am, mp, pl, le, e., .t, tx, xt]
To get the value returned from file(), you just need to pass a string in the nGram parameters, and call file(string) within it (because file() already returns a string).
private String file(String fileName){...}
private void nGram(String valueFromFile){...}
public static void main(String[] args) throws Exception {
...
Example e = new Example(fileName, k);
e.nGram(e.file(fileName));
}
Solution: Called the method nGram(line) in the method file().
package ie.gmit.sw;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Example {
private String fileName;
private static int k;
public Example(String fileName, int k) {
this.fileName = fileName;
this.k = k;
}
public static String file(String fileName) throws IOException {
//Open the file.
FileReader fr = new FileReader(fileName);
Scanner inFile = new Scanner(fr);
// Read lines from the file till end of file
while (inFile.hasNext()) {
// Read the next line.
String line = inFile.nextLine();
// Display the line.
//System.out.println(line);
nGram(line);
}
// Close the file.
inFile.close();
return fileName;
}
private static void nGram(String j) throws IOException{
List<String> ngrams = new ArrayList<>();
for (int i = 0; i <= j.length() - k; i++) {
ngrams.add(j.substring(i, i + k));
}
System.out.println(ngrams);
}
//Working
// private static void run() throws FileNotFoundException {
// // Open the file.
// FileReader fr = new FileReader(fileName);
// Scanner inFile = new Scanner(fr);
//
// // Read lines from the file till end of file
// while (inFile.hasNext()) {
// // Read the next line.
// String line = inFile.nextLine();
// // Display the line.
// System.out.println(line);
//
// List<String> ngrams = new ArrayList<>();
// for (int i = 0; i <= line.length() - k; i++) {
// ngrams.add(line.substring(i, i + k));
// }
// System.out.println(ngrams);
// }
//
// // Close the file.
// inFile.close();
// }
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter file: ");
String fileName = scanner.nextLine();
System.out.println("Enter kmers: ");
int k = scanner.nextInt();
scanner.close();
Example e = new Example(fileName, k);
file(fileName);
}
}
A simple data file which contains
1908,Souths,Easts,Souths,Cumberland,Y,14,12,4000
1909,Souths,Balmain,Souths,Wests,N
Each line represents a season of premiership and has the following format: year, premiers, runners up, minor premiers, wooden spooners, Grand Final held, winning score,
losing score, crowd
I know how to store a data into an array and use the delimiter, but I am not exactly sure how to store EACH data item by a comma into separate arrays? Some suggestions and what particular code to be used would be nice.
UPDATE:
I just added the code but it still didn't work. Here's the code:
import java.io.*;
import java.util.Scanner;
public class GrandFinal {
public static Scanner file;
public static String[] array = new String[1000];
public static void main(String[] args) throws FileNotFoundException {
File myfile = new File("NRLdata.txt");
file = new Scanner (myfile);
Scanner s = file.useDelimiter(",");
int i = 0;
while (s.hasNext()) {
i++;
array[i] = s.next();
}
for(int j=0; j<array.length; j++) {
if(array[j] == null)
;
else if(array[j].contains("Y"))
System.out.println(array[j] + " ");
}
}
}
Here you go. Use ArrayList. Its dynamic and convenient.
BufferedReader br = null;
ArrayList<String> al = new ArrayList();
String line = "";
try {
br = new BufferedReader(new FileReader("NRLdata.txt"));
while ((line = br.readLine()) != null) {
al.add(line);
}
} catch (Exception e) {
e.printStackTrace();
}
for (int i = 0; i < al.size(); i++) {
System.out.println(al.get(i));
}
What does not work in your case ?
Because your season array is empty. You need to define the length, for ex:
private static String[] season = new String[5];
This is not right because you don't know how many lines you are going to store. Which is why I suggested you to Use ArrayList.
After working around a bit, I have come up with following code:
private static File file;
private static BufferedReader counterReader = null;
private static BufferedReader fileReader = null;
public static void main(String[] args) {
try {
file = new File("C:\\Users\\rohitd\\Desktop\\NRLdata.txt");
counterReader = new BufferedReader(new FileReader(file));
int numberOfLine = 0;
String line = null;
try {
while ((line = counterReader.readLine()) != null) {
numberOfLine++;
}
String[][] storeAnswer = new String[9][numberOfLine];
int counter = 0;
fileReader = new BufferedReader(new FileReader(file));
while ((line = fileReader.readLine()) != null) {
String[] temp = line.split(",");
for (int j = 0; j < temp.length; j++) {
storeAnswer[j][counter] = temp[j];
System.out.println(storeAnswer[j][counter]);
}
counter++;
}
} catch (IOException e) {
e.printStackTrace();
}
}
catch (FileNotFoundException e) {
System.out.println("Unable to read file");
}
}
I have added counterReader and fileReader; which are used for counting number of lines and then reading the actual lines. The storeAnswer 2d array contains the information you need.
I hope the answer is better now.
I'm trying to read a csv file into either an ArrayList or a String [][] array. In this I'm trying to read it into a list and then form the list, using a tokenizer, into an array. The csv file have 7 columns (A - G) and 961 rows (1-961). My for loop for the 2D array keeps returning a null pointer, but I think it should be working..
public class FoodFacts
{
private static BufferedReader textIn;
private static BufferedReader foodFacts;
static int numberOfLines = 0;
static String [][] foodArray;
public static String aFact;
static int NUM_COL = 7;
static int NUM_ROW = 961;
// Make a random number to pull a line
static Random r = new Random();
public static void main(String[] args)
{
try
{
textIn = new BufferedReader(new InputStreamReader(System.in));
foodFacts= new BufferedReader(new FileReader("foodfacts.csv"));
Scanner factFile = new Scanner(foodFacts);
List<String> facts = new ArrayList<String>();
String fact;
System.out.println("Please type in the food you wish to know about.");
String request = textIn.readLine();
while ( factFile.hasNextLine()){
fact = factFile.nextLine();
StringTokenizer st2 = new StringTokenizer(fact, ",");
//facts.add(fact);
numberOfLines++;
while (st2.hasMoreElements()){
for ( int j = 0; j < NUM_COL ; j++) {
for (int i = 0; i < NUM_ROW ; i++){
foodArray [j][i]= st2.nextToken(); //NULL POINTER HERE
System.out.println(foodArray[j][i]);
}
}
}
}
}
catch (IOException e)
{
System.out.println ("Error, problem reading text file!");
e.printStackTrace();
}
}
}
Initialize your foodArray as foodArray = new String[NUM_ROW][NUM_COL]; before using it.
Also, there is no need for inner for loop as you are reading one row at a time.
use numberOfLines as row:
while ( factFile.hasNextLine() && numberOfLines < NUM_ROW){
fact = input.nextLine();
StringTokenizer st2 = new StringTokenizer(fact, ",") ;
//facts.add(fact);
while (st2.hasMoreElements()){
for ( int j = 0; j < NUM_COL ; j++) {
foodArray [numberOfLines][j]= st2.nextToken();
System.out.println(foodArray[numberOfLines][i]);
}
}
numberOfLines++;
}
Alternatively, I think you can use split to get all columns as once e.g.
while ( factFile.hasNextLine() && numberOfLines < NUM_ROW){
fact = input.nextLine();
foodArray [numberOfLines++] = fact.split(",");
}
One question: Is there any specific purpose for declaring all variables as static class variables? Most of them fit as local variable inside the method e.g. numberOfLines?
You can use this String [][] foodArray = csvreadString(filename); method. It actually reads the file twice, but I don't know how to get the csv dimension without reading the data (you need the dimension in order to initialize the array), and this is very fast in comparison to other methods that I tried.
static public class PairInt {
int rows = 0;
int columns = 0;
}
static PairInt getCsvSize(String filename) throws Throwable {
PairInt csvSize = new PairInt();
BufferedReader reader = new BufferedReader(new FileReader(new File(filename)));
String line;
while ((line = reader.readLine()) != null) {
if (csvSize.columns == 0) {
csvSize.columns = line.split(",").length;
}
csvSize.rows++;
}
reader.close();
return csvSize;
}
static String[][] csvreadString(String filename) throws Throwable {
PairInt csvSize = getCsvSize(filename);
String[][] data = new String[csvSize.rows][csvSize.columns];
BufferedReader reader = new BufferedReader(new FileReader(new File(filename)));
for (int i = 0; i < csvSize.rows; i++) {
data[i] = reader.readLine().split(",");
}
return data;
}
I'm running into an issue when converting some code for another project and was hoping for a bit of help. In the 'readFile' method, I am trying to parse a String to integers when I read the file. However, it is giving me the error 'array found, but int required'
import java.util.*;
import java.io.*;
public class JavaApplication1
{
static int [] matrix = new int [10];
static Scanner input = new Scanner(System.in);
public static void main(String[] args) throws IOException
{
String fileName = "Integers.txt";
// read the file
readFile(fileName);
// print the matrix
printArray(fileName, matrix);
}
// Read File
public static void readFile(String fileName) throws IOException
{
String line = "";
FileInputStream inputStream = new FileInputStream(fileName);
Scanner scanner = new Scanner(inputStream);
DataInputStream in = new DataInputStream(inputStream);
BufferedReader bf = new BufferedReader(new InputStreamReader(in));
int lineCount = 0;
String[] numbers;
while ((line = bf.readLine()) != null)
{
numbers = line.split(" ");
for (int i = 0; i < 10; i++)
{
matrix[lineCount][i] = Integer.parseInt(numbers[i]);
}
lineCount++;
}
bf.close();
}
public static void printToFile(String fileName, String output) throws IOException
{
java.io.File file = new java.io.File(fileName);
try (PrintWriter writer = new PrintWriter(file))
{
writer.print(output);
}
}
public static void printArray(String fileName, int [] array)
{
System.out.println("The matrix is:");
for (int i = 0; i < 10; i++)
{
System.out.println();
}
System.out.println();
}
}
matrix is an array of type int, which means matrix[lineCount] is an int.
You are tryng to do matrix[lineCount][i] which is getting the place i of an int.
That is why you are getting that error.
I guess you wanted matrix to be int[][] matrix = new int[10][10];
matrix[lineCount][i] = Integer.parseInt(numbers[i]);
is wrong.
Should be either
matrix[lineCount]= Integer.parseInt(numbers[i]);
OR
matrix[i]= Integer.parseInt(numbers[i]);
I am trying to read a text file in java using FileReader and BufferedReader classes. Following an online tutorial I made two classes, one called ReadFile and one FileData.
Then I tried to extract a small part of the text file (i.e. between lines "ENTITIES" and "ENDSEC"). Finally l would like to tell the program to find a specific line between the above-mentioned and store it as an Xvalue, which I could use later.
I am really struggling to figure out how to do the last part...any help would be very much apprciated!
//FileData Class
package textfiles;
import java.io.IOException;
public class FileData {
public static void main (String[] args) throws IOException {
String file_name = "C:/Point.txt";
try {
ReadFile file = new ReadFile (file_name);
String[] aryLines = file.OpenFile();
int i;
for ( i=0; i < aryLines.length; i++ ) {
System.out.println( aryLines[ i ] ) ;
}
}
catch (IOException e) {
System.out.println(e.getMessage() );
}
}
}
// ReadFile Class
package textfiles;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
import java.lang.String;
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];
String nextline = "";
int i;
// String Xvalue;
for (i=0; i < numberOfLines; i++) {
String oneline = textReader.readLine();
int j = 0;
if (oneline.equals("ENTITIES")) {
nextline = oneline;
System.out.println(oneline);
while (!nextline.equals("ENDSEC")) {
nextline = textReader.readLine();
textData[j] = nextline;
// xvalue = ..........
j = j + 1;
i = i+1;
}
}
//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;
}
}
I don't know what line you are specifically looking for but here are a few methods you might want to use to do such operation:
private static String START_LINE = "ENTITIES";
private static String END_LINE = "ENDSEC";
public static List<String> getSpecificLines(Srting filename) throws IOException{
List<String> specificLines = new LinkedList<String>();
Scanner sc = null;
try {
boolean foundStartLine = false;
boolean foundEndLine = false;
sc = new Scanner(new BufferedReader(new FileReader(filename)));
while (!foundEndLine && sc.hasNext()) {
String line = sc.nextLine();
foundStartLine = foundStartLine || line.equals(START_LINE);
foundEndLine = foundEndLine || line.equals(END_LINE);
if(foundStartLine && !foundEndLine){
specificLines.add(line);
}
}
} finally {
if (sc != null) {
sc.close();
}
}
return specificLines;
}
public static String getSpecificLine(List<String> specificLines){
for(String line : specificLines){
if(isSpecific(line)){
return line;
}
}
return null;
}
public static boolean isSpecific(String line){
// What makes the String special??
}
When I get it right you want to store every line between ENTITIES and ENDSEC?
If yes you could simply define a StringBuffer and append everything which is in between these to keywords.
// This could you would put outside the while loop
StringBuffer xValues = new StringBuffer();
// This would be in the while loop and you append all the lines in the buffer
xValues.append(nextline);
If you want to store more specific data in between these to keywords then you probably need to work with Regular Expressions and get out the data you need and put it into a designed DataStructure (A class you've defined by our own).
And btw. I think you could read the file much easier with the following code:
BufferedReader reader = new BufferedReader(new
InputStreamReader(this.getClass().getResourceAsStream(filename)));
try {
while ((line = reader.readLine()) != null) {
if(line.equals("ENTITIES") {
...
}
} (IOException e) {
System.out.println("IO Exception. Couldn't Read the file!");
}
Then you don't have to read first how many lines the file has. You just start reading till the end :).
EDIT:
I still don't know if I understand that right. So if ENTITIES POINT 10 1333.888 20 333.5555 ENDSEC is one line then you could work with the split(" ") Method.
Let me explain with an example:
String line = "";
String[] parts = line.split(" ");
float xValue = parts[2]; // would store 10
float yValue = parts[3]; // would store 1333.888
float zValue = parts[4]; // would store 20
float ... = parts[5]; // would store 333.5555
EDIT2:
Or is every point (x, y, ..) on another line?!
So the file content is like that:
ENTITIES POINT
10
1333.888 // <-- you want this one as xValue
20
333.5555 // <-- and this one as yvalue?
ENDSEC
BufferedReader reader = new BufferedReader(new
InputStreamReader(this.getClass().getResourceAsStream(filename)));
try {
while ((line = reader.readLine()) != null) {
if(line.equals("ENTITIES") {
// read next line
line = reader.readLine();
if(line.equals("10") {
// read next line to get the value
line = reader.readLine(); // read next line to get the value
float xValue = Float.parseFloat(line);
}
line = reader.readLine();
if(line.equals("20") {
// read next line to get the value
line = reader.readLine();
float yValue = Float.parseFloaT(line);
}
}
} (IOException e) {
System.out.println("IO Exception. Couldn't Read the file!");
}
If you have several ENTITIES in the file you need to create a class which stores the xValue, yValue or you could use the Point class. Then you would create an ArrayList of these Points and just append them..