Displaying text retrieved from a Java class - java

I'm a beginner in Java. I have a 2 Java file that will passed the text retrieved from one Java file to the main Java file. But it doesnt seems to be working.
Main.java
import java.io.IOException;
public class LSAalgo extends Preprocessing {
public static void main(String[] args) throws IOException {
Preprocessing x = new Preprocessing(?);
}
}
Retrieve.java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Preprocessing {
public void preprocessing(String text) throws IOException
{
BufferedReader in = new BufferedReader(new FileReader("input7.txt"));
String line;
while((line = in.readLine()) != null)
{
System.out.println(line);
}
in.close();
}
}
Please help. Thanks.

You are just printing the text in console only. If you want to return complete text from one method to other just change your method return type to String (Since you are returning text) from void. Next change your code to
public String preprocessing() throws IOException
{
BufferedReader in = new BufferedReader(new FileReader("input7.txt"));
String line = "";
while((line = in.readLine()) != null)
{
System.out.println(line);
line += line;//appending complete text
}
in.close();
return line;//returning text
}
In main(-) change code to call preprocessing() method of Preprocessing class.
Preprocessing x = new Preprocessing();
String text = x.preprocessing();//getting text from Preprocessing class

Related

java update txt file content line by line

I am trying to update a txt file in place, namely without creating a temp file or writing a file in a new file destination but I've tried all the solutions on stack overflow and none of these have worked so far.
It always give me an empty file as result. it simply delete all the content of the source file.
So I am trying to modify the following code, which takes two files as input, in order to take only one input (the file source) but without success.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
public class CopyFiles {
private static void copyFile(String sourceFileName, String destinationFileName) {
try (BufferedReader br = new BufferedReader(new FileReader(sourceFileName));
PrintWriter pw = new PrintWriter(new FileWriter(destinationFileName))) {
String line;
while ((line = br.readLine()) != null) {
line += " ENDING ";
pw.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String destinationFileName = "destination.csv";
String sourceFileName = "source.csv";
copyFile(sourceFileName, destinationFileName);
}
}

Junit test by passing file path string and IOException handling inside private method

I have a private method called from the main() method to which I am passing the input file path as an argument. My code-under-test is the main() method. Somewhere in the middle of the private method, the file is read and some operations performed.
How can I:
1. Pass the file path of String type ("src/test/resources/test.txt") as an argument. I am getting FileNotFoundException if I pass the file path.
2. How can I test an IOException that is handled in private method on not finding the file?
Adding my code snippets here:
Code under Test:
public class MyApp {
public static void main(String[] args) {
new MyApp().readFile(args);
}
private void readFile(String[] args) {
if (args != null) {
String file = args[0];
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
// More business logic here for processing that line
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}
Test for main:
#Test
void mainTest() {
String[] args = {"/test_input.txt"};
MyApp.main(args);
assertNotNull(<some_object_after_processing>);
}
To get file path you can use suitable way mentation in this link
There is no need to check any assertion for main method.
If the test case is completed successfully then it passed.
Thank you for raising your queries! First, you need to change your application code because you are reading a single file from the args[0] position then why you are going to read the strings array [File Array or collection of files].
1] Create 'resources' folder in your project:
Right-click on project and create a folder with name 'resources'.
2] Create 'test.txt' into the 'resources' folder.
3] Modified code:
package com.application;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class MyApp {
public static void main(String[] args) {
new MyApp().readFile("resources/Test.txt");
}
private void readFile(String fileName) {
if (fileName != null) {
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
// More business logic here for processing that line
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}
Here, You can pass a fileName directly to the method. I hope that it will help you to resolve your first query.

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.

JSON sorting large data sets

http://openlibrary.org/search.json?q=prolog
I have the above API which i am going to be implementing in a android application.
Is there a way to grab from the json on the fly. a specific field for instance:
if i search the above i would need the Author, Language, suggested_title and ISBN. for each result. (so in the above case there would be 100 results.)
which i the plan on storing in a array in the format of
Title|author|lang|ISBN
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
public class main {
public static void main(String[] args) throws IOException
{
URL testing = new URL("http://openlibrary.org/search.json?q=prolog");
BufferedReader in = new BufferedReader(
new InputStreamReader(testing.openStream()));
String inputLine;
String test = null;
int i =1;
while ((inputLine = in.readLine()) != null)
{
if (inputLine == "\"title_suggest\":")
{
test = inputLine;
}
}
in.close();
System.out.println(test);
}
}
appears to work
as i could then add test to array location [x][y]

Java 8 "Missing return type" error for lambda expression

I am new to Java 8 and trying to understand the concepts. I am getting
Missing return type
error for the Lambda expression I am passing to ReadTheFile method.
BufferReaderProcessor
package java8.programs;
import java.io.BufferedReader;
import java.io.IOException;
#FunctionalInterface
public interface BufferReadderProcessor {
String process(BufferedReader br) throws IOException;
}
MainJava
package java8.programs;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class MainJava {
public static void main(String[] args) throws IOException {
MainJava obj = new MainJava();
String message = obj.ReadTheFIle((BufferedReader br) -> {
while (br.readLine()!=null)
br.readLine();
});
System.out.println(message);
}
public String ReadTheFIle(BufferReadderProcessor bp) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(new File("G:\\DemoJavaFile.txt")));
return bp.process(br);
}
}
Your lambda expression implements the BufferReaderProcessor's String process(BufferedReader br) method, so it should return a String.
For example, assuming you wish to return the data you read from the BufferedReader :
String message = obj.ReadTheFIle((BufferedReader br) -> {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
}
return sb.toString();
});

Categories