Buffered reader not accessable by other methods - java

Sorry if this is obvious, I am inexperienced with Java. I have 2 methods, one that creates a BufferedReader, and one that processes it. However, the processing method can not access the BufferedReader, even though it is in a public method. Am I doing something wrong?
package textfiles;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
public class ReadFile {
private String path;
public ReadFile(String filePath) {
path = filePath;
}
public void Open() throws IOException {
FileReader read = new FileReader(path);
BufferedReader buff = new BufferedReader(read);
}
public String[] OpenFile() throws IOException {
int numberOfLines = readLines();
String[] textData = new String[numberOfLines];
int i;
for (i=0; i < numberOfLines; i++) {
textData[i] = buff.readLine();
}
buff.close();
return textData;
}
int readLines() throws IOException {
FileReader linedFile = new FileReader(path);
BufferedReader findLines = new BufferedReader(linedFile);
String lines;
int noLines = 0;
while ((lines = findLines.readLine()) != null) {
noLines++;
}
findLines.close();
return noLines;
}
}

Define BufferedReader at instance level just after declaring your path variable like
BufferedReader buff;
And in your method open, initialize it like
buff = new BufferedReader(read);

Your code should return compile time error as buff undefined variable. So declare it as instance variable and use it in any method directly.

Related

Junit mocking files using jmockit

I am trying to test my java code using jmockit for the first time and I am really confused. I have a method that reads a file and returns the line of strings that reads from the file as a list.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Reader {
public static final int LIMIT = -1;
public static final int EMPTY_FILE = 0;
private String delimiter = ",";
public Reader() {}
public List<List<String>> readFile(String fileName, String delimiter) throws IOException {
List<List<String>> rawData = new ArrayList<>();
File input = new File(fileName);
if (!delimiter.isEmpty())
this.delimiter = delimiter;
if (input.length() == EMPTY_FILE) {
throw new IOException("File is empty. Check file and try again.");
}
BufferedReader reader = new BufferedReader(new FileReader(input));
String line;
while ((line = reader.readLine()) != null) {
List<String> lineData = Arrays.asList(line.split(this.delimiter, LIMIT));
rawData.add(lineData);
}
return rawData;
}
}
I am trying to test this code using mocked readers and bufferedReader but without any luck. Obviously I am doing something wrong but I can't figure out how to do it properly.
What I want is to create a mocked file that will be read and test it like its empty or non empty.
What I have tried so far :
class ReaderTest {
static final String FILENAME = "input.txt";
#Injectable
File mockedFile;
#Mocked
BufferedReader mockedBufferedReader;
#Mocked
FileReader mockedFileReader;
#Test
void readNonEmptyInputFileShouldDoNothing() throws FileNotFoundException {
new Expectations(File.class) {{
new File(anyString);
result = mockedFile;
}};
new Expectations(BufferedReader.class) {{
new FileReader(anyString);
result = mockedFileReader;
new BufferedReader(mockedFileReader);
result = mockedBufferedReader;
}};
Reader reader = new Reader();
Assertions.assertDoesNotThrow(() ->
reader.readFile(FILENAME, FieldsConstants.DELIMITER));
}
}
This test gives me an IllegalArgumentException error:
Invalid Class argument for partial mocking (use a MockUp instead): class java.io.File
I managed to solve my issue using PowerMock and EasyMock API. The only issue i faced was that in the beginning i was using Junit5 and PowerMock wasn't working as intended. I switched to Junit4 and everything worked out just fine. Just some sample code if anyone is interested:
#RunWith(PowerMockRunner.class)
#PrepareForTest({Reader.class})
#PowerMockIgnore({"javax.management.*", "javax.script.*"})
public class ReaderTest {
public static final String TEST_LINE = "2,Ned,Flanders,SELLER,,,LINE_A,Springfield,12.8,TRUE";
public static final String FILENAME = "file_name";
public static final int LIMIT = -1;
private static List<List<String>> tmpList;
#BeforeClass
public static void beforeAll() {
List<String> tmpLine = Arrays.asList(TEST_LINE.split(FieldsConstants.DELIMITER, LIMIT));
tmpList = new ArrayList<>();
tmpList.add(tmpLine);
}
#Test
public void readNonEmptyInputFileShouldDoNothing() throws Exception {
File mockFile = createMockAndExpectNew(File.class, FILENAME);
FileReader mockFileReader = createMockAndExpectNew(FileReader.class, mockFile);
BufferedReader mockBufferedReader = createMockAndExpectNew(BufferedReader.class, mockFileReader);
Reader reader = new Reader();
expect(mockFile.length()).andReturn((long) 100);
expect(mockBufferedReader.readLine()).andReturn(TEST_LINE);
expect(mockBufferedReader.readLine()).andReturn(null);
replayAll();
assertEquals(reader.readFile(FILENAME, ""), tmpList);
verifyAll();
}
}

FileWriter / BufferedReader Java word finder

I have this code set up and I am trying to write a program that looks through a file and finds a specific hidden secret word then replaces the word with "found!" then re-prints the text file in the console. I know how to use reader and writer but I am unsure how i can use them in unison to do this. Code is as follows:
Reader Class:
package Main;
import java.io.*;
public class Read {
private static String line;
FileReader in;
File file;
public Read() {
line = "";
}
public void readFile() throws IOException {
file = new File("C:examplePathName\\ReadWriteExp.txt");
in = new FileReader(file);
BufferedReader br = new BufferedReader(in);
while((line = br.readLine()) != null) {
System.out.println(line);
}
in.close();
}
public String getLine() {
return line;
}
public File getFile() {
return file;
}
}
Writer(change) class:
package Main;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
public class Change {
public static void main(String[] args) throws IOException{
Read r = new Read();
String line = r.getLine();
FileWriter fw = new FileWriter(r.getFile());
while(line != null) {
if(line.equals("example")) {
fw.write("found!");
}
System.out.println(line);
}
}
}
Am i on the right path or should i combine both of these into one class. Also is this the proper way of writing to a specific line in a text file?
If the file is a reasonable size, you can read it into memory, change what you need and write it back out again:
public static void replaceOccurrences(String match, String replacement, Path path) throws IOException {
Files.write(path, Files.lines(path).map(l -> {
if(l.contains(match)) {
return l.replace(match, replacement);
} else {
return l;
}
}).collect(Collectors.toList()));
}
Alternatively, if you know that the search term occurs only once and you just need to find the position of the occurrence, use the following:
try(BufferedReader reader = Files.newBufferedReader(path)) {
int lineIndex = 0;
String line;
while(!(line = reader.readLine()).contains(match)) {
lineIndex++;
}
System.out.println(lineIndex); // line which contains match, 0-indexed
System.out.println(line.indexOf(match)); // starting position of match in line, 0-indexed
}
If all you have to do is print the converted text to system out (rather than writing it out to a file), the second class isn't really needed. You can accomplish what you need in the readFile() method of the Read class:
public void readFile() throws IOException {
file = new File("C:examplePathName\\ReadWriteExp.txt");
in = new FileReader(file);
BufferedReader br = new BufferedReader(in);
while((line = br.readLine()) != null) {
System.out.println(line.replaceAll("example", "found!"));
}
in.close();
}
There are a lot of other tweaks you could make, but that's the core of the functionality you specified in your question.

Error: Could not find or load main class ReadFile recieved when attempting to run code [duplicate]

This question already has answers here:
Running a Java Program
(5 answers)
Closed 8 years ago.
When I run some code I have compiled (with no errors) I receive the following error:
Error: Could not find or load main class ReadFile
The code I am trying to run is the file ReadFile.java:
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
public class ReadFile {
public static void main(String[] args) throws IOException {
String file_name = "hello.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() );
}
}
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;
}
}
and hello.txt is as follows:
Hello World
Hello Solar System
Hello Galaxy
I am a beginner and am not sure why I am returned with this error, can anyone help?
First of all, change directories to the location of your source file..
Use the Java Compiler to compile the source file to a .class file
javac ReadFile.java
Now use Java to run the resulting .class file...
java ReadFile
(Note, I didn't have a file to read, but that wasn't my goal)
**** WARNING ****
This will only work if the ReadFile.java file does not start with a package declaration. If it does, it will change the way that the class has to be run!!

ReadFile cannot be resolved to a type

I am consider a rookie and I have searched for hours on the internet to solve my problem but still no luck.
I really want to understand java and if you could explain some detail that will be highly grateful.
The problem is in this line
ReadFile file = ReadFile(file_name);
error message : "ReadFile cannot be resolved to a type."
Here is my code: FileData.java
package textfiles;
import java.io.IOException;
public class FileData {
public static void main (String[] args) throws IOException {
String file_name = "D:/java/readfile/test.txt";
try {
ReadFile file = 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() );
}
}
}
And this is my other code: ReadFile.java
package textfiles;
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;
}
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;
}
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;
}
}
Try this:
ReadFile file = new ReadFile(file_name);
In order to initialize an object with it's class name you should use the new key word like this:
ClassName objName = new ClassName(arguments);
From the rest of your code seems you know the notion, nevertheless I refer you (or possible future visitors) to this page.

I cannot find the error

I am following the tutorial here and I have been trying to get this working for two days now. I get this error message when compiling FileData.
FileData.java:13: error: cannot find symbol
ReadFile file = new ReadFile(file_name);
^
symbol: class ReadFile
location: class FileData
FileData.java:13: error: cannot find symbol
ReadFile file = new ReadFile(file_name);
^
symbol: class ReadFile
location: class FileData
Any assistance would be greatly appreciated.
The code follows:
package textfiles;
import java.io.IOException;
public class FileData
{
public static void main(String[] args) throws IOException
{
String file_name = "C:/test.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() );
}
}
}
package textfiles;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
public class ReadFile
{
private String path;
public ReadFile (String file_path) //ReadFile Method
{
path = file_path;
}
public String[] OpenFile() throws IOException //OpenFile method
{
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
int numberOfLines = readLine();
String[] textData = new String[numberOfLines];
int i;
for (i=0; i < numberOfLines; i++)
{
textData[i] = textReader.readLine();
}
textReader.close();
return textData;
}
int readLine() throws IOException //readLines Method
{
FileReader file_to_read = new FileReader(path);
BufferedReader bf = new BufferedReader(file_to_read);
String aLines;
int numberOfLines = 0;
while ((aLines = bf.readLine()) !=null)
{
numberOfLines++;
}
bf.close();
return numberOfLines;
}
}
The problem is JAVA COMPILER is looking for CLASS FILE {ReadFile.class} inside the folder textfiles so follow this to get compile,
1--> compile the ReadFile using this
javac -d . ReadFile.java
2--> compile the FileData using this
javac -d . FileData.java
NOTE: The purpose of this
-d
is it will create appropriate packages during compilation.

Categories