I know this is a bit naive. How to unit test this piece of code without giving physical file as input.
I am new to mockito and unit testing. So I am not sure. Please help.
public static String fileToString(File file) throws IOException
{
BufferedReader br = new BufferedReader(new FileReader(file));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append("\n");
line = br.readLine();
}
return sb.toString();
} finally {
br.close();
}
}
You can create a file as part of the test, no need to mock it out.
JUnit does have a nice functionality for creating files used for testing and automatically cleaning them up using the TemporaryFolder rule.
public class MyTestClass {
#Rule
public TemporaryFolder folder = new TemporaryFolder();
#Test
public void myTest() {
// this folder gets cleaned up automatically by JUnit
File file = folder.newFile("someTestFile.txt");
// populate the file
// run your test
}
}
You should probably refactor your method. As you realized, a method taking a file as input isn't easily testable. Also, it seems to be static, which doesn't help testability. If you rewrite your method as :
public String fileToString(BufferedReader input) throws IOException
it will be much easier to test. You separate your business logic form the technicalities of reading a file. As I understand it, your business logic is reading a stream and ensuring the line endings are unix style.
If you do that, your method will be testable. You also make it more generic : it can now read from a file, from a URL, or from any kind of stream. Better code, easier to test ...
Why do you wanna mock a file? Mocking java.io.File is a bad idea as it has loads of native stuff. I would advice you to ensure that a minimalist text file is available in classpath when the unit tests are run. You can convert this file to text and confirm the output.
you could use combination of ByteArrayInputStream and BufferedReader class, to make your required file within your code. So there wouldn't be any need to create a real File on your system. What would happen if you don't have enough permission --based of some specific circumstances -- to create a file. On the code below, you create your own desirable content of your file:
public static void main(String a[]){
String str = "converting to input stream"+
"\n and this is second line";
byte[] content = str.getBytes();
InputStream is = null;
BufferedReader bfReader = null;
try {
is = new ByteArrayInputStream(content);
bfReader = new BufferedReader(new InputStreamReader(is));
String temp = null;
while((temp = bfReader.readLine()) != null){
System.out.println(temp);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try{
if(is != null) is.close();
} catch (Exception ex){
}
}
}
Related
I'm pretty new in the programming world, and i can't find a good explanation on how to to load a txt file to a string variable in java using eclpise.
So far, from what i have been able to understand, i am supposed to use the StdIn class, and i know that the txt file need to be located in my eclipse workspace (outside the source folder) but i don't know what excatly i need to write in the code to get the given file to load into the variable.
I could really use some help with this.
Although I'm not a Java expert, I'm pretty sure this is the information you're looking for It looks like this:
static String readFile(String path, Charset encoding)
throws IOException
{
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);
}
Basically all languages provide you with some methods to read from the file system you're in. Hope that does it for you!
Good luck with your project!
to read a file and store it in a String you can do it by using either String or StringBuilder:
you need to define BufferedReader to with constructor of FileReader to pass the name of the file and make it ready to read from file.
use StringBuilder to append every line of result to it.
when the reading finished add the result to String data.
public static void main(String[] args) {
String data = "";
try {
BufferedReader br = new BufferedReader(new FileReader("filename"));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append("\n");
line = br.readLine();
}
data = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
}
So the problem is I try to read the configuration file that is packed inside the .jar which works fine but then when it comes to writing to the file the file can not be found yet they are using the same
getClass().getResource(Path);
it only seems to work with the input stream.
Here is all the code of my IO class.
package com;
public class IO {
public boolean CheckStream () {
String LineRead;
try {
InputStream IS = getClass().getResourceAsStream("Config.txt");
InputStreamReader ISR = new InputStreamReader (IS,Charset.forName("UTf-8"));
BufferedReader BR = new BufferedReader(ISR);
if ((LineRead = BR.readLine()) != null) {
BR.close();
return true;
}
IS.close();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
public void Write (String Path, String [] ThingsToWrite) throws FileNotFoundException {
OutputStream Out = new FileOutputStream (getClass().getResource(Path).getPath());
PrintStream PS = new PrintStream (Out);
for (int i = 0; i < ThingsToWrite.length; i ++) {
PS.print(ThingsToWrite[i]);
}
PS.close();
}
}
Any Help is greatly appreciated thanks.
You can't just write to a file within a jar file - it's not a file in the regular sense.
While you could unpack the whole jar file, write the new content, then pack it up again, it would be better to redesign so that you don't need to update the jar file.
For example, you might have a regular local file which is used if it's present, but then fall back to reading from the jar file otherwise. Then you only need to write to the local file.
A method returns a String in comma separated format. For example, the returned String can be like the one given below.
Tarantino,50,M,USA\n Carey Mulligan,27,F,UK\n Gong Li,45,F,China
I will need to get this String and write it into a CSV file. I'll have to insert a header and a footer for this file as well.
For example, when I open the file, the contents for the above data will be
Name,Age,Gender,Country
Tarantino,50,M,USA
Carey Mulligan,27,F,UK
Gong Li,45,F,China
How do we do that ? Are there any open source libraries to do this task ?
CSV format is not very well defined. You don't have to write headers for the file. Instead it is pretty SIMPLE format. Data values are separated using commas or semicolon or space etc.
You just have to write your own simple method that writes your string to a file on local computer using FileOutputStream or Writer in java.io package.
You can use this as a learning example.
I used BufferedReader because he will take care about line separators, but you can also use #split method, and write the resulting tokens.
import java.io.*;
public class Tests {
public static void main(String[] args) {
File file = new File("out.csv");
BufferedWriter out = null;
try {
out = new BufferedWriter(new FileWriter(file));
String string = "Tarantino,50,M,USA\n Carey Mulligan,27,F,UK\n Gong Li,45,F,China";
BufferedReader reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(string.getBytes())));
String line;
while ((line = reader.readLine()) != null) {
out.write(line.trim());
out.newLine();
}
}
catch (IOException e) {
// log something
e.printStackTrace();
}
finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
// ignored
}
}
}
}
}
This is pretty simple
String str = "Tarantino,50,M,USA\n Carey Mulligan,27,F,UK\n Gong Li,45,F,China";
PrintWriter pr = new PrintWriter(new FileWriter(new File("test.csv"), true));
String arr[] = str.split("\\n");
// splited the string by new line provided with the string
pr.println("Name,Age,Gender,Country");
// header written first and rest of data appended
for(String s : arr){
pr.println(s);
}
pr.close();
don't forget to close the stream in finally block and handle the exception
I am working on a simple save system for my game, which involves three methods, init load and save.
This is my first time trying out reading and writing to/from a file, so I am not sure if I am doing this correctly, therefore I request assistance.
I want to do this:
When the game starts, init is called. If the file saves does not exist, it is created, if it does, load is called.
Later on in the game, save will be called, and variables will be written to the file, line by line (I am using two in this example.)
However, I am stuck on the load function. I have no idea what do past the point I am on. Which is why I am asking, if it is possible to select a certain line from a file, and change the variable to that specific line.
Here is my code, like I said, I have no idea if I am doing this correctly, so help is appreciated.
private File saves = new File("saves.txt");
private void init(){
PrintWriter pw = null;
if(!saves.exists()){
try {
pw = new PrintWriter(new File("saves.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}else{
try {
load();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void save(){
PrintWriter pw = null;
try {
pw = new PrintWriter(new FileOutputStream(new File("saves.txt"), true));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
pw.println(player.coinBank);
pw.println(player.ammo);
pw.close();
}
public void load() throws IOException{
BufferedReader br = new BufferedReader(new FileReader(saves));
String line;
while ((line = br.readLine()) != null) {
}
}
I was thinking of maybe having an array, parsing the string from the text file into a integer, putting it into the array, and then have the variables equal the values from the array.
Seems like your file is a key=value structure, I suggest you'll use Properties object in java.
Here's a good example.
Your file will look like this:
player.coinBank=123
player.ammo=456
To save:
Properties prop = new Properties();
prop.setProperty("player.coinBank", player.getCoinBank());
prop.setProperty("player.ammo", player.getAmmo());
//save properties to project root folder
prop.store(new FileOutputStream("player.properties"), null);
Then you'll load it like this:
Properties prop = new Properties();
prop.load(new FileInputStream("player.properties"));
//get the property value and print it out
System.out.println(prop.getProperty("player.coinBank"));
System.out.println(prop.getProperty("player.ammo"));
Reading and writing are pretty much symmetric.
You're writing player.coinBank as the first line of the file, and player.ammo as the second line. So, when reading, you should read the first line and assign it to player.coinBank, then read the second line and assign it to player.ammo:
public void load() throws IOException{
try (BufferedReader br = new BufferedReader(new FileReader(saves))) {
player.coinBank = br.readLine();
player.ammo = br.readLine();
}
}
Note the use of the try-with-resources statement here, which makes sure the reader is closed, whatever happens in the method. You should also use this construct when writing to the file.
I have to use a method whose signature is like this
aMethod(FileInputStream);
I call that method like this
FileInputStream inputStream = new FileInputStream(someTextFile);
aMethod(inputStream);
I want to remove/edit some char which is being read from someTextFile before it being passed into aMethod(inputStream);
I cannot change aMethod's signature or overload it. And, it just take a InputStream.
If method taking a string as param, then I wouldn't be asking this question.
I am InputStream noob. Please advise.
you can convert a string into input stream
String str = "Converted stuff from reading the other inputfile and modifying it";
InputStream is = new ByteArrayInputStream(str.getBytes());
Here is something that might help. It will grab your .txt file. Then it will load it and go through line by line. You have to fill in the commented areas to do what you want.
public void parseFile() {
String inputLine;
String filename = "YOURFILE.txt";
Thread thisThread = Thread.currentThread();
ClassLoader loader = thisThread.getContextClassLoader();
InputStream is = loader.getResourceAsStream(filename);
try {
FileWriter fstream = new FileWriter("path/to/NEWFILE.txt");
BufferedWriter out = new BufferedWriter(fstream);
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
while((inputLine = reader.readLine()) != null) {
String[] str = inputLine.split("\t");
if(/* IF WHAT YOU WANT IS IN THE FILE ADD IT */) {
// DO SOMETHING OR ADD WHAT YOU WANT
out.append(str);
out.newLine();
}
}
reader.close();
out.close();
} catch (Exception e) {
e.getMessage();
}
}
Have you looked at another class FilterInputStream which also extends InputStream which may fit into your requirement?
From the documentation for the class
A FilterInputStream contains some other input stream, which it uses as its basic source of data, possibly transforming the data along the way or providing additional functionality.
Also have a look at this question which also seems to be similar to your question.