Java : How can I test save method? - java

I have a following save method, but I dont know how to verify that the method is working correctly. How can I verify it in Test Class ??
static void saveFile(List<String> contents, String path){
File file = new File(path);
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)));
for(String data : contents){
pw.println(data);
}
}
Sorry, contents is not String, but List. But is there no need to make test class ?? because it is constructed by tested java method.

For testing, you may consider a test framework such as jUnit and write your test case. In your specific case, you could write something as follows:
public class TestCase {
#Test
public void test() throws IOException {
String contents = "the your content";
String path = "the your path";
// call teh metod
saveFile(contents, path);
// tacke a reference to the file
File file = new File(path);
// I assert that the file is not empty
Assert.assertTrue(file.length() > 0);
// I assert that the file content is the same of the contents variable
Assert.assertSame(Files.readLines(file, Charset.defaultCharset()).stream().reduce("", (s , s2) -> s+s2),contents);
}
static void saveFile(String contents, String path) throws IOException {
File file = new File(path);
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)));
pw.println(contents);
}
}
In this way, you have a framework to check if the your code works as you expect. If this isn't sufficient, you should look into a mock framework such as Mockito.

Remove FileWriter from you method like this
static void saveFile(List<String> contents, Writer writer){
PrintWriter pw = new PrintWriter(new BufferedWriter(writer));
for(String data : contents){
pw.println(data);
}
pw.flush();
}
In your JUnit test method use StringWriter for checking your saving logic
#Test
void testWriter() {
StringWriter writer = new StringWriter();
saveFile(Arrays.asList("test content", "test content2"), writer);
assertEquals("test content\ntest content2\n", writer.toString());
}
and in your real code
...
Writer writer = new FileWriter(new File(path));
saveFile(Arrays.asList("real content", "real content2"), writer);
...

Related

Unable to write to the file, Created in java using File class

Class MakeDirectory contains the constructor, and in the constructor I created a directory and inside that directory I created a file. But I am unable to write anything to the newly created file, even though the file and directory have been generated successfully. Can anyone help me figure out why I am not able to write to the file Anything.txt?
public class MakeDirectory {
MakeDirectory() throws IOException{
// Creates Directory
File mydir= new File("MyDir");
mydir.mkdir();
// Creates new file object
File myfile = new File("MyDir","Anyfile.txt");
//Create actual file Anyfile.txt inside the directory
PrintWriter pr= new PrintWriter(myfile);
pr.write("This file is created through java");
}
public static void main(String args[]) throws IOException {
new MakeDirectory();
}
}
If you want to use PrintWriter you need to know that it is not automatically flushing. After you write you need to flush. Also, don't forget to close your PrintWriter!
PrintWriter pw = new PrintWriter(myFile);
pw.write("text");
pw.flush();
pw.close();
An approach available in Java 7 employs the try-with-resources construct. Using this feature, the code would look like the following:
try (PrintWriter pw = new PrintWriter("myFile")) {
pw.write("text");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
With BufferedWriter you can just write the strings, arrays or characters data directly to the file:
void makeDirectory() throws IOException {
// Creates Directory
File mydir = new File("MyDir");
mydir.mkdir();
// Creates new file object
File myfile = new File("MyDir", "Anyfile.txt");
//Create actual file Anyfile.txt inside the directory
BufferedWriter bw = new BufferedWriter(new FileWriter(myfile.getAbsoluteFile()));
String str = "This file is created through java";
bw.write(str);
bw.close();
}

Why is is my program not pulling in the files from the folder

I have a program that is suppose to read all the files in my folder and combine the files into on file and place them into a new folder. Some of the files are not being pulled in and I do not know why.
The file names are wonder1.txt, wonder2.txt, wonder3.txt, and wonder4.txt and the folder name is Alice, but only a few of the files are actually in the new folder.
import java.io.*;
import java.util.Scanner;
import java.util.*;
import java.lang.*;
import java.io.PrintWriter;
public class alice {
public static void main(String[] args) throws FileNotFoundException, IOException {
File folder = new File("/Users/DAndre/Desktop/Alice");
//Reads in all the files in that folder
for (final File fileEntry : folder.listFiles()) {
String fileName = fileEntry.getAbsolutePath();
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
StringBuilder stringBuilder = new StringBuilder();
String line = br.readLine();
while (line != null) {
stringBuilder.append(line);
stringBuilder.append("\n");
line = br.readLine();
}
/**
* Pass original file content as string to another method which
* creates new file with same content.
*/
newFile(stringBuilder.toString());
} finally {
br.close();
}
}
}
public static void newFile(String fileContent) {
try {
String newFileLocation = "/Users/DAndre/Desktop/final/final_copy.txt";
PrintWriter writer = new PrintWriter(newFileLocation);
writer.write(fileContent);//Writes original file content into new file
writer.close();
System.out.println("File Created");
} catch (Exception e) {
e.printStackTrace();
}
}
}
The problem with your solution is that you haven't initialize PrintWriter in append mode, because of which the new file gets overwritten with the content of the last file that was written.
public static void newFile(String fileContent) {
try {
String newFileLocation = "C:\\Users\\Shayan\\Desktop\\files2\\final_copy.txt";
PrintWriter writer = new PrintWriter(new FileOutputStream(new File(newFileLocation), true /* append = true */));
writer.write(fileContent);//Writes original file content into new file
writer.close();
System.out.println("File Created");
} catch (Exception e) {
e.printStackTrace();
}
}
The last argument in the constructor of FileOututStream is set to true, indicating that it should be opened in append mode.
You need to change
PrintWriter writer = new PrintWriter(newFileLocation);
to
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(newFileLocation, true)))
Little explanation: append meant to write it additively, on the contrary write overrides the existing file. In your code you are creating a new file including one of your wonders, but on next iteration the file is recreated. So the content of previous wonder is gone.
With the change PrintWriter object is not recreating the file, instead it writes content to a BufferedWriter which also transfers the stream to an append able FileWriter object.
Little suggest: do not create a PrintWriter object on each iteration.
Second little suggest: You don't need PrintWriter. BufferedWriter itself is good enough as far as I see.

PrintWriter class in a separate method

Hello working on a small program that writes data to a file. I am using a if else statement for validation so I need the PrintWriter and FileWriter class/declaration in a separate method. I then call this method with the constructor of the main class. The problem I am having is when I moved the Printwriter class to it's own method I can no longer access it from my button click aciton l istener.
CODE:
private void OpenFilePW(){
try{
String inputFileName = "addressBook.txt";
FileWriter fw = new FileWriter(inputFileName, true);
PrintWriter outputFile = new PrintWriter(fw);
}catch(IOException error){
JOptionPane.showConfirmDialog(null, error);
}
}
When using outputFile. I get an error because it can't find outputFile. Why wont' this work?
define the PrintWriter as an instance variable in your main calss
not sure what are you trying to use this for
but make it public to get it working or don't use any modifier if you are working in the same class
so your code should be
public class MyClass
{
public PrintWriter outputFile;
.....
}
and then instantiate the instance when you get to the method
outputFile = new PrintWriter(fw);
First (by convention), Java method names start with a lower case letter. Second, you aren't returning the PrintWriter you're assigning it to a method local variable -
private PrintWriter openFilePW(){
try{
String inputFileName = "addressBook.txt";
FileWriter fw = new FileWriter(inputFileName, true);
return new PrintWriter(fw);
} catch(IOException error) {
JOptionPane.showConfirmDialog(null, error);
}
return null;
}
Alternatively, you could assign the PrintWriter to a class level variable,
private PrintWriter outputFile = null;
private void openFilePW(){
try{
String inputFileName = "addressBook.txt";
FileWriter fw = new FileWriter(inputFileName, true);
outputFile = new PrintWriter(fw);
} catch(IOException error) {
JOptionPane.showConfirmDialog(null, error);
}
}

Writing order string into text file

This is only write "test 2" in the text file.
How to write the first line will be "test 1", and the second line will be "test 2" in the text file.
if(s1.equals("test 1")&&s2.equals("test 2")){
WriteNameOrderInFile.nameOfFirstOrderForImage(s1);
WriteNameOrderInFile.nameOfSecondOrderForImage(s2);
WriteNameOrderInFile class:
public class WriteNameOrderInFile(){
public static void nameOfFirstOrder(String s) throws IOException {
String nameFileDoctor="C:/append info.txt";
FileOutputStream fos = new FileOutputStream(nameFileDoctor);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
bw.write(s);
bw.newLine();
bw.flush();
bw.close();
}
public static void nameOfSecondOrder(String s) throws IOException {
File file= new File("C:/append info.txt");
FileOutputStream fos2= new FileOutputStream(file,true);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos2));
bw.write(s);
bw.newLine();
bw.flush();
bw.close();
}
Even if the solution is only to call the correct methods, here are some improvements for your code:
public class WriteNameOrderInFile {
public static void writeToFile(String text, boolean append) {
File file = new File("C:/append info.txt");
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file, append))) {
bw.write(text);
bw.newLine();
} catch (IOException e) {
// do some exception handling
System.err.println("Can't write to file!");
}
}
public static void main(String[] args) {
// just a sample call with the code you provided
String s1 = "test 1";
String s2 = "test 2";
if (s1.equals("test 1") && s2.equals("test 2")) {
writeToFile(s1, false); // boolean is false, so write (replace) text
writeToFile(s2, true); // append is true, so append text
}
}
}
Some explanations to the improvements of the code:
Your two methods are only different on writing text to a file and appending text to a file. So consider using one method writeToFile and give it an append-boolean
Instead of OutputStreamWriter and FileOutputStream consider using FileWriter
If you're using Java with version >= 7, use try-with-resource statement. You can easily get rid of trying to close streams in a good manner.
BufferedWriter.flush() is also not needed, since it will be done while closing the file (what is done by the try-with-resource statement)

java write data to file without erasing the old content

how can i
write data to file without erasing the old content
Use new FileOutputStream(file, true). This will open file in "append" mode which will append all data written to the stream to the end of that file.
You mean "how do you append to a file"? Look for an [append-version of a constructor][1] of your File writing class, e.g.:
public FileWriter(String fileName,
boolean append)
throws IOException
Use this constructor and pass true for the append parameter.
[1]: http://download.oracle.com/javase/6/docs/api/java/io/FileWriter.html#FileWriter(java.io.File, boolean)
if you used the new one in Java 7, you can use this way
try (BufferedWriter writer = Files.newBufferedWriter(outFile, StandardCharsets.UTF_8, StandardOpenOption.APPEND))
in this code i use append (true) but my old date erase and new data overwrite on it please give me solution on it
public class FileOperation {
private static FileReader fileReader;
private static FileWriter fileWriter;
private static BufferedReader bufferedReader;
private static BufferedWriter bufferedWriter;
private static PrintWriter writer;
public static File file = new File("C:\\StudentInfo\\com\\education\\students\\file\\managing\\v1_0\\Student.txt");
public FileOperation() throws IOException {
fileReader = new FileReader(file);
fileWriter = new FileWriter(file, true);
bufferedReader = new BufferedReader(fileReader);
bufferedWriter = new BufferedWriter(fileWriter);
// FileOperation fo =new FileOperation();
}
public boolean enrollSudnents(ArrayList<Student> studentList) {
try {
writer = new PrintWriter(file);
writer.print("");
bufferedWriter = new BufferedWriter(new FileWriter(file));
for (Student s : studentList) {
String nameNumberString = String.valueOf(s.getRoll() + "!" + s.getFirstName() + "!" + s.getLastName()
+ "!" + s.getClassName() + "!" + s.getAddress() + "\n");
bufferedWriter.write(nameNumberString);
}
return true;
} catch (Exception e) {
return false;
} finally {
try {
bufferedWriter.close();
fileWriter.close();
} catch (Exception e) {
// logger.info("Exception Found In Adding data");
}
}
}

Categories

Resources