I'm trying to write a test class with jUnit 4 to test Separating class. Separating class has 3 methods to open a file, separate its content into 3 files and close the file. The SeparatingTest doesn't work. It separates the content of the file but it doesn't pass the test. I am new to jUnit test. Can you help me with that please?
separating class:
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.*;
import java.util.*;
public class Separating {
public static BufferedReader input;
public static PrintWriter output14;
public static PrintWriter output15;
public static PrintWriter output16;
public static void openFiles() throws FileNotFoundException, IOException {
input= new BufferedReader(new FileReader("numbers.txt"));
output14 = new PrintWriter(new FileOutputStream("numbers14.txt"));
output15 = new PrintWriter(new FileOutputStream("numbers15.txt"));
output16 = new PrintWriter(new FileOutputStream("numbers16.txt"));
}
public void separate(BufferedReader input, PrintWriter output14,
PrintWriter output15, PrintWriter output16) throws IOException, InvalidUoBException {
String line;
while ((line = input.readLine()) != null) {
if (line.startsWith("14")) {
output14.write(line + "\n");
count14++;
} else if (line.startsWith("15")) {
output15.write(line + "\n");
count15++;
} else if (line.startsWith("16")) {
output16.write(line + "\n");
count16++;
} else {
throw new InvalidUoBException("not 14, 15, 16");
}
}
}
public static void closeFiles() throws IOException {
input.close();
output14.close();
output15.close();
output16.close();
}
public static void main(String[] args) throws IOException {
try {
Separating br = new Separating();
openFiles();
br.separate(input, output14, output15, output16);
closeFiles();
System.out.println("Successfuly separated the file");
} catch (InvalidUoBException e) {
System.out.println("UoB number does not start with 14, 15 or 16!");
} catch (FileNotFoundException e) {
System.out.println("File was not found");
System.out.println("or could not be opened.");
} catch (IOException e) {
System.out.println("Error reading from file.");
}
}
}
test class:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import static junit.framework.TestCase.assertEquals;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
public class SeparatingTest extends Separating {
public SeparatingTest() {
}
public static BufferedReader inputTest;
public static PrintWriter outputTest14;
public static PrintWriter outputTest15;
public static PrintWriter outputTest16;
public static BufferedReader inputTest14;
public static BufferedReader inputTest15;
public static BufferedReader inputTest16;
#BeforeClass
public static void setUpClass() {
}
#AfterClass
public static void tearDownClass() {
}
#Before
public void setUp() throws FileNotFoundException {
inputTest = new BufferedReader(new FileReader("testnumbers.txt"));
outputTest14 = new PrintWriter(new FileOutputStream("testnumbers14.txt"));
outputTest15 = new PrintWriter(new FileOutputStream("testnumbers15.txt"));
outputTest16 = new PrintWriter(new FileOutputStream("testnumbers16.txt"));
inputTest14 = new BufferedReader(new FileReader("testnumbers14.txt"));
inputTest15 = new BufferedReader(new FileReader("testnumbers15.txt"));
inputTest16 = new BufferedReader(new FileReader("testnumbers16.txt"));
}
#After
public void tearDown() throws IOException {
inputTest.close();
outputTest14.close();
outputTest15.close();
outputTest16.close();
inputTest14.close();
inputTest15.close();
inputTest16.close();
}
#Test
public void testSeparate() throws Exception {
/*testnumbers.txt: 14451024
15752601
16148923
*/
Separating br200 = new Separating();
br200.separateStudents(inputTest, outputTest14, outputTest15, outputTest16);
assertEquals(inputTest14.readLine(), "18451024");
assertEquals(inputTest15.readLine(), "15752601");
assertEquals(inputTest16.readLine(), "16148923");
}
}
Related
I have a file called "ParkPhotos.txt" and inside I have 12 names of some parks, for example "AmericanSamoa1989_photo.jpg". I want to replace the "_photo.jpg" to "_info.txt", but I am struggling. In the code I was able to read the file, but I am not sure how to replace it.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class FileNameChange {
public static void main(String[] args) throws IOException
{
readFileValues();
}
public static void readFileValues() throws IOException
{
try {
File aFile = new File("ParkPhotos.txt");
Scanner inFile = new Scanner(aFile);
while (inFile.hasNextLine())
{
String parkNames = inFile.nextLine();
System.out.println(parkNames);
}
inFile.close();
} catch (FileNotFoundException e)
{
System.out.println("An error has occurred");
e.printStackTrace();
}
}
}
You can convert to a new content and write it to the current file. For example:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Scanner;
public class FileNameChange {
public static void main(String[] args) throws URISyntaxException {
String newContent = readFileValues();
writeFileValues(newContent);
}
public static String readFileValues() {
StringBuilder newContent = new StringBuilder();
try {
URL url = FileNameChange.class.getClassLoader().getResource("ParkPhotos.txt");
File aFile = new File(url.toURI());
Scanner inFile = new Scanner(aFile);
while (inFile.hasNextLine()) {
String parkName = inFile.nextLine();
if (parkName == null || parkName.isEmpty()) {
continue;
}
newContent.append(parkName.replace("_photo.jpg", "_info.txt"))
.append(System.lineSeparator());
}
inFile.close();
} catch (FileNotFoundException | URISyntaxException e) {
e.printStackTrace();
}
return newContent.toString();
}
public static void writeFileValues(String content) throws URISyntaxException {
URL url = FileNameChange.class.getClassLoader().getResource("ParkPhotos.txt");
File aFile = new File(url.toURI());
try (FileWriter writer = new FileWriter(aFile)) {
writer.write(content);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Note: the file will be written at build folder. For example: example_1/build/resources/main
I have a program which does the following:
Stores a file name in Main method
Passes that file to the below method(StreamParser)from Main
Method StreamParser reads that file as Stream
StreamParser should return Stream
In main method when I call forEach on purchaseEventStream it gives an error in line
purchaseEventStream.forEach(purchaseEvent -> {
Exception in thread "main" java.lang.IllegalStateException: source already consumed or
closed
at java.base/java.util.stream.AbstractPipeline.sourceSpliterator(AbstractPipeline.java:409)
at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.base/java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:497)
at com.cognitree.internship.streamprocessing.Main.main(Main.java:22)
StreamParser Class
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class StreamParser {
public Stream<PurchaseEvent> parser(String fileName) throws IOException {
Stream<PurchaseEvent> purchaseEventStream;
try (Stream<String> lines = Files.lines(Paths.get(fileName))) {
purchaseEventStream= lines.map(line -> {
String[] fields = line.split(",");
PurchaseEvent finalPurchaseEvent = new PurchaseEvent();
finalPurchaseEvent.setSessionId(fields[0]);
finalPurchaseEvent.setTimeStamp(fields[1]);
finalPurchaseEvent.setItemId(fields[2]);
finalPurchaseEvent.setPrice(fields[3]);
finalPurchaseEvent.setQuantity(fields[4]);
return finalPurchaseEvent;
});
return purchaseEventStream;
}
}
}
Main Class
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) throws IOException {
OutputStreamWriter outputStream = new OutputStreamWriter(new
FileOutputStream("output1.txt"));
String file = "/Users/mohit/intern-mohit/yoochoose-buys.dat";
StreamParser streamParser = new StreamParser();
List<ReportGenerator> reports = new ArrayList<>();
PurchaseEventCount purchaseEventCount = new PurchaseEventCount();
QuantityPerSession quantityPerSession = new QuantityPerSession();
SessionCount sessionCount = new SessionCount();
reports.add(purchaseEventCount);
reports.add(sessionCount);
reports.add(quantityPerSession);
Stream<PurchaseEvent> purchaseEventStream = streamParser.parser(file);
purchaseEventStream.forEach(purchaseEvent -> {
for (ReportGenerator report : reports) {
report.generateReports(purchaseEvent);
}
});
reports.forEach(report -> {
try {
report.printReports(outputStream);
} catch (IOException e) {
e.printStackTrace();
}
});
}
}
Why am i getting the error?
A stream in java is not a collection. It does not store data. You should create and return a collection from method parser() in class StreamParser and then create a stream from the returned collection.
I rewrote your StreamParser class to return a List.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
public class StreamParser {
public List<PurchaseEvent> parser(String fileName) throws IOException {
List<PurchaseEvent> purchaseEventStream = Files.lines(Paths.get(fileName))
.map(line -> {
String[] fields = line.split(",");
PurchaseEvent finalPurchaseEvent = new PurchaseEvent();
finalPurchaseEvent.setSessionId(fields[0]);
finalPurchaseEvent.setTimeStamp(fields[1]);
finalPurchaseEvent.setItemId(fields[2]);
finalPurchaseEvent.setPrice(fields[3]);
finalPurchaseEvent.setQuantity(fields[4]);
return finalPurchaseEvent;
})
.collect(Collectors.toList());
return purchaseEventStream;
}
}
And I changed your Main class accordingly.
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
OutputStreamWriter outputStream = new OutputStreamWriter(new FileOutputStream("output1.txt"));
String file = "/Users/mohit/intern-mohit/yoochoose-buys.dat";
StreamParser streamParser = new StreamParser();
List<ReportGenerator> reports = new ArrayList<>();
PurchaseEventCount purchaseEventCount = new PurchaseEventCount();
QuantityPerSession quantityPerSession = new QuantityPerSession();
SessionCount sessionCount = new SessionCount();
reports.add(purchaseEventCount);
reports.add(sessionCount);
reports.add(quantityPerSession);
List<PurchaseEvent> purchaseEventStream = streamParser.parser(file);
purchaseEventStream.forEach(purchaseEvent -> {
for (ReportGenerator report : reports) {
report.generateReports(purchaseEvent);
}
});
reports.forEach(report -> {
try {
report.printReports(outputStream);
}
catch (IOException e) {
e.printStackTrace();
}
});
}
}
I'm trying to make two objects that are able to read and write to a text file. The problem happens when I execute the program. The text file gets erased. Why is this happening and how do I fix this?
CODE:
Object to read text files:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Reader {
public static String fromFile;
public static FileReader fr;
public static BufferedReader file;
public Reader(String fileName) throws IOException, FileNotFoundException {
fr = new FileReader(fileName);
file = new BufferedReader(fr);
}
public void readFile() throws IOException {
while((fromFile = file.readLine()) != null) {
System.out.println(fromFile);
}
}
}
Object to write to text files:
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
public class Writer {
public static FileWriter fw;
public static BufferedWriter file;
public Writer(String fileName) throws IOException, FileNotFoundException {
fw = new FileWriter(fileName);
file = new BufferedWriter(fw);
}
}
Main method to create Reader and Writer objects and use the Reader to read the text file:
import java.io.IOException;
public class Main {
public static Writer toFile;
public static Reader fromFile;
public static String fileName = "test123.txt";
public static void main(String[] args) throws IOException {
toFile = new Writer(fileName);
fromFile = new Reader(fileName);
fromFile.readFile();
}
}
This is just my suggestion.
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
public static String fileName = "test123.txt";
Read rd=new Read();
rd.reader(filename);
}
}
public class Read
{
public void reader(String filename)
{
FileReader fr=new FileReader(filename);
BufferedReader bfr=new BufferedWriter (fr);
String text="";
String line=reader.readLine();
while(line!=null)
{
text+=line;
line=reader.readLine();
}
System.out.println(text);
}
fr.close();
bfr.close();
}
So I am having problems reading (loading into array) this file
For this project, download the text file weblog.txt
http://www.santarosa.edu/~lmeade/weblog.txt
Note: To download this file, right click on the link and select SAVE AS.
I saved in on my desktop
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
public class project4 {
static Scanner scan=new Scanner(System.in);
public static final String INPUT_FILENAME="weblog.txt";
public static final String OUTPUT_FILENAME="sorted_weblog.txt";
public static final int MAX=2990;
public static String[] fileContent=new String[MAX];
public static int count=0;
public static void main(String[] args) {
readFile();
sortFileContent();
writeFile();
}
public static void readFile() {
try {
File f= new File(INPUT_FILENAME);
Scanner br = new Scanner(f);
String sCurrentLine;
while (br.hasNext()) {
sCurrentLine = br.nextLine();
fileContent[count++]=sCurrentLine;
}
} catch (FileNotFoundException e) {
System.out.println("File not Found");
}
}
private static void sortFileContent() {
Arrays.sort(fileContent);
}
private static void writeFile() {
PrintWriter out;
try {
out = new PrintWriter(new File(OUTPUT_FILENAME));
for (int i = 0; i < count; i++) {
out.println(fileContent[i]);
}
out.close();
} catch (FileNotFoundException e) {
System.out.println("File not Found");
}
}
}
I was making a pretty simple jar to unzip a zip and run the jar that was inside of it. The problem I've run into is that it doesn't do anything at all.
This is the main, and only class file for the jar. The manifest does point correctly to it, and it loads without errors.
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.BufferedOutputStream;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import static java.lang.Integer.parseInt;
import java.net.URLConnection;
import java.net.URL;
import java.util.zip.ZipFile;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.Enumeration;
import sign.signlink;
import java.nio.file.*;
import java.io.FileReader;
public class ClientUpdater {
private String fileToExtractNew = "/client.zip";
private String getJarDir() throws FileNotFoundException, IOException{
String linebuf="",verStr="";
FileInputStream fis = new FileInputStream("/runLocationURL.txt");
BufferedReader br= new BufferedReader(new InputStreamReader(fis));
while ((linebuf = br.readLine()) != null) {
verStr = linebuf;
}
return verStr;
}
public static void main(String[] args) {
System.out.println("start");
}
private void unZip() {
System.out.println("unzipping");
try {
ZipEntry zipEntry;
//client
BufferedInputStream bufferedInputStreamNew = new BufferedInputStream(new FileInputStream(this.fileToExtractNew));
ZipInputStream zipInputStreamNew = new ZipInputStream(bufferedInputStreamNew);
//client
while ((zipEntry = zipInputStreamNew.getNextEntry()) != null) {
String stringNew = zipEntry.getName();
File fileNew = new File(this.getJarDir() + File.separator + stringNew);
if (zipEntry.isDirectory()) {
new File(this.getJarDir() + zipEntry.getName()).mkdirs();
continue;
}
if (zipEntry.getName().equals(this.fileToExtractNew)) {
this.unzipNew(zipInputStreamNew, this.fileToExtractNew);
break;
}
new File(fileNew.getParent()).mkdirs();
this.unzipNew(zipInputStreamNew, this.getJarDir() + zipEntry.getName());
}
zipInputStreamNew.close();
}
catch (Exception var1_2) {
var1_2.printStackTrace();
}
}
private void unzipNew(ZipInputStream zipInputStreamNew, String stringNew) throws IOException {
System.out.println("unzipping new");
FileOutputStream fileOutputStreamNew = new FileOutputStream(stringNew);
byte[] arrby = new byte[4024];
int n = 0;
while ((n = zipInputStreamNew.read(arrby)) != -1) {
fileOutputStreamNew.write(arrby, 0, n);
}
fileOutputStreamNew.close();
Runtime.getRuntime().exec("java -jar " + getJarDir() + "/Project Pk Client.jar");
System.exit(0);
}
}
It shows the "Start" message, but not the other 2, so it never reaches those methods. Is it because they aren't being called? I'm still learning Java.
You actually have to call your other methods from main. Right now, all you are telling the computer to do is print start and then exit. Functions do not get called simply by existing.
It seems based on a quick glance that you just need to add unzip(); to your main function, right after the System.out.println line.
To do this, you need to say that those other methods are static, so you need to say private static void unZip() instead of private void unZip(). Do this for your other methods too.
import java.io.*;
import static java.lang.Integer.parseInt;
import java.net.URLConnection;
import java.net.URL;
import java.util.zip.ZipFile;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.Enumeration;
import sign.signlink;
import java.nio.file.*;
public class ClientUpdater {
private String fileToExtractNew = "/client.zip";
private static String getJarDir() throws FileNotFoundException, IOException{
String linebuf="",verStr="";
FileInputStream fis = new FileInputStream("/runLocationURL.txt");
BufferedReader br= new BufferedReader(new InputStreamReader(fis));
while ((linebuf = br.readLine()) != null) {
verStr = linebuf;
}
return verStr;
}
public static void main(String[] args) {
System.out.println("start");
unZip();
}
private static void unZip() {
System.out.println("unzipping");
try {
ZipEntry zipEntry;
//client
BufferedInputStream bufferedInputStreamNew = new BufferedInputStream(new FileInputStream(this.fileToExtractNew));
ZipInputStream zipInputStreamNew = new ZipInputStream(bufferedInputStreamNew);
//client
while ((zipEntry = zipInputStreamNew.getNextEntry()) != null) {
String stringNew = zipEntry.getName();
File fileNew = new File(this.getJarDir() + File.separator + stringNew);
if (zipEntry.isDirectory()) {
new File(this.getJarDir() + zipEntry.getName()).mkdirs();
continue;
}
if (zipEntry.getName().equals(this.fileToExtractNew)) {
this.unzipNew(zipInputStreamNew, this.fileToExtractNew);
break;
}
new File(fileNew.getParent()).mkdirs();
this.unzipNew(zipInputStreamNew, this.getJarDir() + zipEntry.getName());
}
zipInputStreamNew.close();
}
catch (Exception var1_2) {
var1_2.printStackTrace();
}
}
private static void unzipNew(ZipInputStream zipInputStreamNew, String stringNew) throws IOException {
System.out.println("unzipping new");
FileOutputStream fileOutputStreamNew = new FileOutputStream(stringNew);
byte[] arrby = new byte[4024];
int n = 0;
while ((n = zipInputStreamNew.read(arrby)) != -1) {
fileOutputStreamNew.write(arrby, 0, n);
}
fileOutputStreamNew.close();
Runtime.getRuntime().exec("java -jar " + getJarDir() + "/Project Pk Client.jar");
System.exit(0);
}
}