Add characters into BufferedReader - java

I would like to create mock test for reading file values into JUnit test.
I'm this code to read text code.
BufferedReader cpuReader = new BufferedReader(new InputStreamReader(new FileInputStream("/opt/test")));
In order to create JUnit test I need to add some dummy data which I need to keep into Java buffer. Just for example (it's completely wrong) I want to do this:
BufferedReader cpuReader = new BufferedReader():
cpuReader.addText("Some text");
// process further this data
Can you show me what is the correct way to add some text into the variable cpuReader when I initialize the Object BufferedReader()?

You should do something like this:
String str = "The string you want for your output";
BuffereReader r = new BufferedReader(new StringReader(str))
Try not to mock files, there are many disadvantages.

You can use a PushbackReader to add text back into the stream:
String textToAdd = "Some text";
PushbackReader cpuReader = new PushbackReader(
new BufferedReader(new InputStreamReader(new FileInputStream("/opt/test"))),
textToAdd.length());
cpuReader.unread(textToAdd.toCharArray());

Here is an example of using a StringReader:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
public class SimpleTest {
public static void main(String[] args) {
// Create a BufferedReader based on a string
String s = "This is my input\nIt has two lines\n";
StringReader strReader = new StringReader(s);
BufferedReader cpuReader = new BufferedReader(strReader);
// Use the BufferedReader, regardless of its source.
String line;
try {
while ((line = cpuReader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Note that once you have created the cupReader, you use it just like you did before, regardless of the fact that it's based on a StringReader.

Another way to do it is to hook up a BufferedReader with a PipedReader like this:
PipedReader pipeR = new PipedReader();
BufferedReader br = new BufferedReader(pipeR);
And then to connect the PipedReader with a PipedWriter like in:
// create a new Piped writer and reader
PipedWriter writer = new PipedWriter();
// connect the reader and the writer
pipeR.connect(writer);
Now (and in a dynamic fashion), whatever data you write using the writer write method, you can also read it via your BufferedReader

Related

Get NullPointerException from calling org.apache.lucene.benchmark.byTask.feeds.TrecGov2Parser.parse

I want to pars GOv2 collection format and I want to use TrecGov2Parser. I find its code in this page. The input file is test file and it contains just one document of GOV2 collection.
This is my code:
public static void writeHTMLText()
{
try
{
FileWriter fw1= new FileWriter(new File("/home/fl/Desktop/GOV_Text/GOV/00.txt"));
BufferedWriter bw1 = new BufferedWriter(fw1);
FileReader fileReader = new FileReader(new File("/home/fl/Desktop/GOV/00"));
BufferedReader br = new BufferedReader(fileReader);
String docs="";
String line;
while((line=br.readLine())!= null )
docs= docs+line+"\n";
DocData docData = new DocData();
DocData result = new TrecGov2Parser().parse(docData,"result00",new TrecContentSource(),new StringBuilder(docs),TrecDocParser.ParsePathType.GOV2);
bw1.write(result.getBody());
br.close();
bw1.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
I got this error.
java.lang.NullPointerException
at org.apache.lucene.benchmark.byTask.feeds.TrecGov2Parser.parse(TrecGov2Parser.java:56)
at LuceneParser.parserInput.writeHTMLText(parserInput.java:63)
I add *lucene-core-3.4.0.jar* and *lucene-benchmark-3.4.0.jar* to my project buildpath.
What do I need to do?
There is no private, protected or public keyword at getHtmlParser(). This means you can call this method only from inside the same package (default/package visibility). The method is intended not to be used by others.

Serialized XML to String

I generate a XML like this. It works fine. But I want to print it out in Eliscps:
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;
public class PersonConstructor {
String info="";
String path="c://myfile/myperson";
// here is my xml object
Person person = new Person();
person.setFirstName("fname");
person.setLastName("lname");
person.setTel("111-111-1111");
person.setAddress("1000 main st.");
//Serializer my object to file.
Serializer serializer = new Persister();
File file = new File(path);
serializer.write(person, file);
//now I want to print out my xml file.I don't know how to do it.
info = file.toString();
System.out.println(info);
}
Should I use output stream?
Use a buffered reader. Just make sure to either add the IOException to your method signature or surround with try/catch block.
BufferedReader in = new BufferedReader(new FileReader(file));
String line = in.readLine();
while(line != null)
{
System.out.println(line);
line = in.readLine();
}
in.close();

Mock File, FileReader and BufferedReader class using Mockito

I got below code in a method which I want to test
File f = map.get("key1")
BuffereReader r = new BufferedReader(new FileReader(f));
String line=null;
do {
line=r.readLine();
} while(r!=null);
I want to mock this operation so that I can pass the content of the file from the JUnit test case. I have done below:
Map fles = Mockito.mock(ConcurrentHashMap.class);
File file = Mockito.mock(File.class);
Mockito.when(files.get("key1")).thenReturn(file);
FileReader fileReader = Mockito.mock(FileReader.class);
BufferedReader bufferedReader = Mockito.mock(BufferedReader.class);
try {
PowerMockito.whenNew(FileReader.class).withArguments(file).thenReturn(fileReader);
PowerMockito.whenNew(BufferedReader.class).withArguments(fileReader).thenReturn(bufferedReader);
PowerMockito.when(bufferedReader.readLine()).thenReturn("line1")
.thenReturn("line2").thenReturn("line3");
} catch (Exception e) {
Assert.fail();
}
So basically I need to pass "line1", "line2" and "line3" as lines from the file which are read by the mocked BufferedReader.
However upon doing that, it failes as NullPointerException when trying to instantiate new FileReader(f) part.
So is it because I can't mock a BufferedReader or the approach is wrong?
Thanks
You could extract a method for doing the actual reading and then test that instead. That would mean you only have to mock a single reader. For example, your code would be something like this:
public void aMethod(){
File f = map.get("key1")
BuffereReader r = new BufferedReader(new FileReader(f));
readStuff(r);
}
public void readStuff(BufferedReader r){
String line=null;
do {
line=r.readLine();
} while(r!=null);
}
then your test code would be more like the following:
BufferedReader bufferedReader = Mockito.mock(BufferedReader.class);
Mockito.when(bufferedReader.readLine()).thenReturn("line1", "line2", "line3");
objUnderTest.readStuff(bufferedReader);
//verify result
You can try PowerMock annotations. Check this : https://code.google.com/p/powermock/wiki/MockConstructor

How to read a text file directly from Internet using Java?

I am trying to read some words from an online text file.
I tried doing something like this
File file = new File("http://www.puzzlers.org/pub/wordlists/pocket.txt");
Scanner scan = new Scanner(file);
but it didn't work, I am getting
http://www.puzzlers.org/pub/wordlists/pocket.txt
as the output and I just want to get all the words.
I know they taught me this back in the day but I don't remember exactly how to do it now, any help is greatly appreciated.
Use an URL instead of File for any access that is not on your local computer.
URL url = new URL("http://www.puzzlers.org/pub/wordlists/pocket.txt");
Scanner s = new Scanner(url.openStream());
Actually, URL is even more generally useful, also for local access (use a file: URL), jar files, and about everything that one can retrieve somehow.
The way above interprets the file in your platforms default encoding. If you want to use the encoding indicated by the server instead, you have to use a URLConnection and parse it's content type, like indicated in the answers to this question.
About your Error, make sure your file compiles without any errors - you need to handle the exceptions. Click the red messages given by your IDE, it should show you a recommendation how to fix it. Do not start a program which does not compile (even if the IDE allows this).
Here with some sample exception-handling:
try {
URL url = new URL("http://www.puzzlers.org/pub/wordlists/pocket.txt");
Scanner s = new Scanner(url.openStream());
// read from your scanner
}
catch(IOException ex) {
// there was some connection problem, or the file did not exist on the server,
// or your URL was not in the right format.
// think about what to do now, and put it here.
ex.printStackTrace(); // for now, simply output it.
}
try something like this
URL u = new URL("http://www.puzzlers.org/pub/wordlists/pocket.txt");
InputStream in = u.openStream();
Then use it as any plain old input stream
What really worked to me: (source: oracle documentation "reading url")
import java.net.*;
import java.io.*;
public class UrlTextfile {
public static void main(String[] args) throws Exception {
URL oracle = new URL("http://yoursite.com/yourfile.txt");
BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
Using Apache Commons IO:
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public static String readURLToString(String url) throws IOException
{
try (InputStream inputStream = new URL(url).openStream())
{
return IOUtils.toString(inputStream, StandardCharsets.UTF_8);
}
}
Use this code to read an Internet resource into a String:
public static String readToString(String targetURL) throws IOException
{
URL url = new URL(targetURL);
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(url.openStream()));
StringBuilder stringBuilder = new StringBuilder();
String inputLine;
while ((inputLine = bufferedReader.readLine()) != null)
{
stringBuilder.append(inputLine);
stringBuilder.append(System.lineSeparator());
}
bufferedReader.close();
return stringBuilder.toString().trim();
}
This is based on here.
For an old school input stream, use this code:
InputStream in = new URL("http://google.com/").openConnection().getInputStream();
I did that in the following way for an image, you should be able to do it for text using similar steps.
// folder & name of image on PC
File fileObj = new File("C:\\Displayable\\imgcopy.jpg");
Boolean testB = fileObj.createNewFile();
System.out.println("Test this file eeeeeeeeeeeeeeeeeeee "+testB);
// image on server
URL url = new URL("http://localhost:8181/POPTEST2/imgone.jpg");
InputStream webIS = url.openStream();
FileOutputStream fo = new FileOutputStream(fileObj);
int c = 0;
do {
c = webIS.read();
System.out.println("==============> " + c);
if (c !=-1) {
fo.write((byte) c);
}
} while(c != -1);
webIS.close();
fo.close();
Alternatively, you can use Guava's Resources object:
URL url = new URL("http://www.puzzlers.org/pub/wordlists/pocket.txt");
List<String> lines = Resources.readLines(url, Charsets.UTF_8);
lines.forEach(System.out::println);
corrected method is deprecated now. It is giving the option
private WeakReference<MyActivity> activityReference;
here solution will useful.

Reading a text file in java

How would I read a .txt file in Java and put every line in an array when every lines contains integers, strings, and doubles? And every line has different amounts of words/numbers.
I'm a complete noob in Java so sorry if this question is a bit stupid.
Thanks
Try the Scanner class which no one knows about but can do almost anything with text.
To get a reader for a file, use
File file = new File ("...path...");
String encoding = "...."; // Encoding of your file
Reader reader = new BufferedReader (new InputStreamReader (
new FileInputStream (file), encoding));
... use reader ...
reader.close ();
You should really specify the encoding or else you will get strange results when you encounter umlauts, Unicode and the like.
Easiest option is to simply use the Apache Commons IO JAR and import the org.apache.commons.io.FileUtils class. There are many possibilities when using this class, but the most obvious would be as follows;
List<String> lines = FileUtils.readLines(new File("untitled.txt"));
It's that easy.
"Don't reinvent the wheel."
The best approach to read a file in Java is to open in, read line by line and process it and close the strea
// Open the file
FileInputStream fstream = new FileInputStream("textfile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console - do what you want to do
System.out.println (strLine);
}
//Close the input stream
fstream.close();
To learn more about how to read file in Java, check out the article.
Your question is not very clear, so I'll only answer for the "read" part :
List<String> lines = new ArrayList<String>();
BufferedReader br = new BufferedReader(new FileReader("fileName"));
String line = br.readLine();
while (line != null)
{
lines.add(line);
line = br.readLine();
}
Common used:
String line = null;
File file = new File( "readme.txt" );
FileReader fr = null;
try
{
fr = new FileReader( file );
}
catch (FileNotFoundException e)
{
System.out.println( "File doesn't exists" );
e.printStackTrace();
}
BufferedReader br = new BufferedReader( fr );
try
{
while( (line = br.readLine()) != null )
{
System.out.println( line );
}
#user248921 first of all, you can store anything in string array , so you can make string array and store a line in array and use value in code whenever you want. you can use the below code to store heterogeneous(containing string, int, boolean,etc) lines in array.
public class user {
public static void main(String x[]) throws IOException{
BufferedReader b=new BufferedReader(new FileReader("<path to file>"));
String[] user=new String[500];
String line="";
while ((line = b.readLine()) != null) {
user[i]=line;
System.out.println(user[1]);
i++;
}
}
}
This is a nice way to work with Streams and Collectors.
List<String> myList;
try(BufferedReader reader = new BufferedReader(new FileReader("yourpath"))){
myList = reader.lines() // This will return a Stream<String>
.collect(Collectors.toList());
}catch(Exception e){
e.printStackTrace();
}
When working with Streams you have also multiple methods to filter, manipulate or reduce your input.
For Java 11 you could use the next short approach:
Path path = Path.of("file.txt");
try (var reader = Files.newBufferedReader(path)) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
Or:
var path = Path.of("file.txt");
List<String> lines = Files.readAllLines(path);
lines.forEach(System.out::println);
Or:
Files.lines(Path.of("file.txt")).forEach(System.out::println);

Categories

Resources