JUnit AssertionFailedError: Text in the file differs in java - java

I am using JUnit Test for testing purposes, but I am facing a problem of AssertionFailedError.
I am using command line arguments to pass Test cases to the main class.
Below is my Main.java code
public class Main {
public static void main(String[] args) throws IOException {
//Storing all the commands, words, files
ArrayList<String> commands = new ArrayList<>();
ArrayList<String> words = new ArrayList<>();
ArrayList<String> files = new ArrayList<>();
for(String arg: args){
if(arg.contains("."))
files.add(arg);
else if(arg.contains("-") && !arg.contains("--"))
commands.add(arg);
else{
if(!arg.contains("--"))
words.add(arg);
}
}
for(String file : files ){
File originalFile = new File(file);
//CHECK IF textFile exists
if(originalFile.exists()){
if(words.size() == 2){
String from = words.get(0), to=words.get(1);
BufferedWriter bw;
//If file exists then check command
for(String command : commands){
if(command.trim().contains("-f")){
File temp = new File("Temp.txt");
temp.createNewFile();
//If Temp.exists
if(temp.exists()){
bw = new BufferedWriter(new FileWriter(temp));
//Fetch all the lines from Orginal File
List<String> lines = Files.readAllLines(Paths.get(originalFile.getName()));
//Add to treemap
TreeMap<Integer,String> tm = new TreeMap<>();
for(int i=0;i<lines.size();i++){
tm.put(i,lines.get(i));
}
//To check first occurence of word in hashmap
for(int i=0;i<tm.size();i++){
String lastLine = tm.get(i);
tm.remove(i);
tm.put(i,lastLine.replaceFirst(from,to));
if(!lastLine.equals(tm.get(i)))
break;
}
//Write treemap to the text file
for(String line: tm.values())
bw.write(line.trim() + "\n");
System.out.println("First Occurence " + originalFile.getName()+ " changed");
bw.close();
originalFile.delete();
temp.renameTo(originalFile);
}else
System.out.println("Error in creating Temp.txt file");
}
}
}
Everything is working fine, the file is created. I dont think there is error in the code. Below is the MainTest.java
public class MainTest {
// Some utilities
private File createInputFile1() throws Exception {
File file1 = new File("Test.txt");
try (FileWriter fileWriter = new FileWriter(file1)) {
fileWriter.write("Dog is an animal");
}
return file1;
}
private String getFileContent(String filename) {
String content = null;
try {
content = new String(Files.readAllBytes(Paths.get(filename)));
} catch (IOException e) {
e.printStackTrace();
}
return content;
}
// Actual test cases
#Test
public void mainTest2() throws Exception {
File inputFile1 = createInputFile1();
String args[] = {"-f", "Dog", "Cat", "--", "Test.txt"};
Main.main(args);
String expected1 = "Cat is an animal".trim();
String actual1 = getFileContent("Test.txt");
assertEquals("The files differ!", expected1, actual1);
assertTrue(Files.exists(Paths.get(inputFile1.getPath() + ".bck")));
}
}
Everything works fine, file Test.txt is created and it has the text in it.
But I am facing this error of AssertionFailedError: The files differ! expected: Cat is an animal[] but was: Cat is an animal[ ]
Why does it differ [] and [ ] ?

Try this, shall help :
String expected1 = "Cat is an animal".trim();
String actual1 = getFileContent("Test.txt").trim();
assertEquals("The files differ!", expected1, actual1);
Since what trim does is
* #return A string whose value is this string, with any leading and trailing white
* space removed, or this string if it has no leading or
* trailing white space.
hence you see a diff of space [ ] and [] with your solution and its resolved using trim in both.

Related

algorithm arraylist remove String duplicates and save to new text file

I am currently writing an algorithm that creates an ArrayList from a .txt file, checks it with a loop for duplicates (where the loop should look like this:
Line one is written to new .txt & boolean found is set to true because the string was already found.
Line 2 is written to new .txt etc.
But if two strings are identical, the duplicate, i.e. the second string should just be ignored and continue with the next one).
public class test {
public static void main(String[] args) throws IOException {
String suche = "88 BETRAG-MINUS VALUE 'M'.";
String suche2 = "88 BETRAG-PLUS VALUE 'P'";
boolean gefunden = false;
File neueDatei = new File("C:\\Dev\\xx.txt");
if (neueDatei.createNewFile()) {
System.out.println("Datei wurde erstellt");
}
if (gefunden == false) {
dateiEinlesen(null, gefunden);
ArrayList<String> arr = null;
inNeueDateischreiben(neueDatei, gefunden, arr, suche, suche2);
}
}
public static void dateiEinlesen(File neueDatei, boolean gefunden) {
BufferedReader reader;
String zeile = null;
try {
reader = new BufferedReader(new FileReader("C:\\Dev\\Test.txt"));
zeile = reader.readLine();
ArrayList<String[]> arr = new ArrayList<String[]>();
while (zeile != null) {
arr.add(zeile.split(" "));
zeile = reader.readLine();
}
System.out.println(arr);
} catch (IOException e) {
System.err.println("Error2 :" + e);
}
}
public static void inNeueDateischreiben(File neueDatei, boolean gefunden, ArrayList<String> arr, String suche2,
String suche22) throws IOException {
FileWriter writer = new FileWriter(suche22);
String lastValue = null;
for (Iterator<String> i = arr.iterator(); i.hasNext();) {
String currentValue = i.next();
if (lastValue != null && currentValue.equals(lastValue)) {
i.remove();
{
writer.write(suche2.toString());
gefunden = true;
}
}
writer.close();
}
}
}
Your variable namings (suche2, suche22) makes reading the code difficult.
Other than that, your writing algorithm looks funny. You only compare adjacent lines while duplicate lines could be anywhere. In addition, writer.write only hits when you find a duplicate. Also how you call it and other things don't look right.
Here are some general steps to write this correctly:
Open the file so you can read it line by line.
Create a file writer
Create a set or dictionary like data structure that enables you to look up items in constant time.
For each line that you read do the following:
Look if the line exists in the dictionary.
If not, write it to the new file
If it already exists in the dictionary, skip to step 4.
Add that line to the dictionary for later comparisons and go to step 4.
When the lines are exhausted close both files.
I suggest, you rewrite your code completely as the current version is very difficult to amend.

check if the word in the set equals word in outside file

I have a set of words and an outside file.
I want to check if a word in the set is already present in the outside file. If the word is already in the file, then do nothing, if the word is not in the outside file already, then add it to the outside file.
This is the code I have written:
public static void toFile(Set<String> vocab, String filename)
{
try
{
for(String vocabWord : vocab)
{
File file = new File(filename);
Scanner sc2 = new Scanner(file);
while(sc2.hasNextLine())
{
String docWord = sc2.nextLine();
if (!(vocabWord.equals(docWord)))
{
FileWriter myWriter = new FileWriter(filename, true);
PrintWriter printWriter = new PrintWriter(myWriter);
printWriter.println(vocabWord);
printWriter.close();
}
else
break;
}
}
}
catch(IOException e)
{
e.printStackTrace();
}
}
I am using three different text documents to test it, have the line "test file one", "test file two", and "test file three".
The output I was expecting was: "test file three" (it is connected with a stop list which one and two are part of, and has been working)
However, when I run it, either with only one of the files or all three consecutively, the file always comes out empty.
I tried changing up things in the method, but nothing has worked, I either get an infinite loop or nothing in the outside file.
I am not sure what I am missing... I would really appreciate any help.
I tried this and added some comments for explanation. I have tested on local machine and it works
public static void toFile(Set<String> vocab, String filename) {
try {
for(String vocabWord : vocab) {
//task for each String in our Set
File file = new File(filename);
Scanner sc2 = new Scanner(file);
boolean exists = false;//lets say it doesn't exist
while(sc2.hasNextLine()) {
//task for each line in the text
//search the whole file first for the word
String docWord = sc2.nextLine();
if (docWord.equals(vocabWord)){
exists = true;
break;
}
}
if (!exists) {
//add the vocabWord only if it doesnt exists
FileWriter myWriter = new FileWriter(filename, true);
PrintWriter printWriter = new PrintWriter(myWriter);
printWriter.println(vocabWord);
printWriter.close();
}
}
} catch(IOException e) {
e.printStackTrace();
}
}
To append the missing vocabulary in order of vocab, you can reduce the file operations
as such:
public static void toFile(Set<String> vocab, String filename) {
try {
Charset charset = Charset.defaultCharset();
Path path = Paths.get(filename);
Set<String> existing = Files.lines(path, charset)
.collect(Collectors.toSet());
if (!existing.isEmpty()) {
try (BufferedWriter bw = Files.newBufferedWriter(path, charset,
StandardOpenOption.APPEND);
PrintWriter printWriter = new PrintWriter(bw)) {
vocab.stream()
.filter(word -> !existing.contains(word))
.forEach(word -> printWriter.println(word));
}
}
} catch (IOException e) {
e.printStackTrace();
}
}

How do I write a method that has an ArrayList and an int as a parameter and returns an ArrayList

I get multiple errors when writing the header of a method that takes an array list and an integer as input.
I have tried several different ways of writing the header for the method. The body is good and gives me what I want but I can't get the header/call name (I don't know what you call the first line of a method) to not throw errors
/**
* Creates Arraylist "list" using prompt user for the input and output file path and sets the file name for the output file to
* p01-runs.txt
*
*/
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the path to your source file: ");
String inPath = scan.nextLine(); // sets inPath to user supplied path
System.out.println("Please enter the path for your source file: ");
String outPath = scan.nextLine() + "p01-runs.txt"; // sets outPath to user supplied input path
ArrayList<Integer> listRunCount = new ArrayList<Integer>();
ArrayList<Integer> list = new ArrayList<Integer>();
/**
* Reads data from input file and populates array with integers.
*/
FileReader fileReader = new FileReader(inPath);
BufferedReader bufferedReader = new BufferedReader(fileReader);
// file writing buffer
PrintWriter printWriter = new PrintWriter(outPath);
System.out.println("Reading file...");
/**
* Reads lines from the file, removes spaces in the line converts the string to
* an integer and adds the integer to the array
*/
File file = new File(inPath);
Scanner in = new Scanner(file);
String temp=null;
while (in.hasNextLine()) {
temp = in.nextLine();
temp = temp.replaceAll("\\s","");
int num = Integer.parseInt(temp);
list.add(num);
}
listRunCount.findRuns(list, RUN_UP);
//********************************************************************************************************
public ArrayList<Integer> findRuns(ArrayList<Integer> list, int RUN_UP){
returns listRunCount;
}
error messages
Multiple markers at this line
- Syntax error on token "int", delete this token
- Syntax error, insert ";" to complete LocalVariableDeclarationStatement
- Integer cannot be resolved to a variable
- ArrayList cannot be resolved to a variable
- Syntax error, insert ";" to complete LocalVariableDeclarationStatement
- Illegal modifier for parameter findRuns; only final is permitted
- Syntax error, insert ") Expression" to complete CastExpression
- Syntax error on token "findRuns", = expected after this token
- Syntax error, insert "VariableDeclarators" to complete
LocalVariableDeclaration
- Syntax error, insert ";" to complete Statement
This sort of thing removes the need for statics. If you run your code from within the static method main() then all class methods, member variables, etc that are called or referenced from within main() must also be declared as static. By doing:
public class Main {
public static void main(String[] args) {
new Main().run();
}
}
eliminates the need for statics. In my opinion to properly do this the run() method within the class should also be passed the args[] parameter:
public class Main {
public static void main(String[] args) {
new Main().run(args);
}
private void run(String[] args) {
// You project code here
}
}
That way any Command Line arguments passed to the application can also be processed from within the run() method. You will find that most people won't use the method name run for this sort of thing since run() is a method name more related to the running of a Thread. A name like startApp() is more appropriate.
public class Main {
public static void main(String[] args) {
new Main().startApp(args);
}
private void startApp(String[] args) {
// You project code here
}
}
With all this in mind your code might look something like this:
public class Main {
public static void main(String[] args) {
new Main().run(args);
}
private void run(String[] args) {
String runCountFileCreated = createListRunCount();
if (!runCountFileCreated.equals("") {
System.out.println(The count file created was: " + runCountFileCreated);
}
else {
System.out.println(A count file was NOT created!);
}
}
/**
* Creates an ArrayList "list" using prompts for the input and output file
* paths and sets the file name for the output (destination) file to an
* incremental format of p01-runs.txt, p02-runs.txt, p03-runs.txt, etc. If
* p01 exists then the file name is incremented to p02, etc. The file name
* is incremented until it is determined that the file name does not exist.
*
* #return (String) The path and file name of the generated destination
* file.
*/
public String createListRunCount() {
String ls = System.lineSeparator();
File file = null;
Scanner scan = new Scanner(System.in);
// Get the source file path from User...
String sourceFile = "";
while (sourceFile.equals("")) {
System.out.print("Please enter the path to your source file." + ls
+ "Enter nothing to cancel this process:" + ls
+ "Source File Path: --> ");
sourceFile = scan.nextLine().trim(); // User Input
/* If nothing was entered (just the enter key was hit)
then exit this method. */
if (sourceFile.equals("")) {
System.out.println("Process CANCELED!");
return "";
}
// See if the supplied file exists...
file = new File(sourceFile);
if (!file.exists()) {
System.out.println("The supplied file Path/Name can not be found!." + ls
+ "[" + sourceFile + "]" + ls + "Please try again...");
sourceFile = "";
}
}
String destinationFile = "";
while (destinationFile.equals("")) {
System.out.print(ls + "Please enter the path to folder where data will be saved." + ls
+ "If the supplied folder path does not exist then an attempt" + ls
+ "will be made to automatically created it. DO NOT supply a" + ls
+ "file name. Enter nothing to cancel this process:" + ls
+ "Destination Folder Path: --> ");
String destinationPath = scan.nextLine();
if (destinationPath.equals("")) {
System.out.println("Process CANCELED!");
return "";
}
// Does supplied path exist. If not then create it...
File fldr = new File(destinationPath);
if (fldr.exists() && fldr.isDirectory()) {
/* Supplied folder exists. Now establish a new incremental file name.
Get the list of files already contained within this folder that
start with p and a number (ex: p01-..., p02--..., p03--..., etc)
*/
String[] files = fldr.list(); // Get a list of files in the supplied folder.
// Are there any files in the supplied folder?
if (files.length > 0) {
//Yes, so process them...
List<String> pFiles = new ArrayList<>();
for (String fileNameString : files) {
if (fileNameString.matches("^p\\d+\\-runs\\.txt$")) {
pFiles.add(fileNameString);
}
}
// Get the largest p file increment number
int largestPnumber = 0;
for (int i = 0; i < pFiles.size(); i++) {
int fileNumber = Integer.parseInt(pFiles.get(i).split("-")[0].replace("p", ""));
if (fileNumber > largestPnumber) {
largestPnumber = fileNumber;
}
}
largestPnumber++; // Increment the largest p file number by 1
// Create the new file name...
String fileName = String.format("p%02d-runs.txt", largestPnumber);
//Create the new destination File path and name string
destinationFile = fldr.getAbsolutePath() + "\\" + fileName;
}
else {
// No, so let's start with p01-runs.txt
destinationFile = fldr.getAbsolutePath() + "\\p01-runs.txt";
}
}
else {
// Supplied folder does not exist so create it.
// User Confirmation of folder creation...
JFrame iFrame = new JFrame();
iFrame.setAlwaysOnTop(true);
iFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
iFrame.setLocationRelativeTo(null);
int res = JOptionPane.showConfirmDialog(iFrame, "The supplied storage folder does not exist!"
+ ls + "Do you want to create it?", "Create Folder?", JOptionPane.YES_NO_OPTION);
iFrame.dispose();
if (res != 0) {
destinationFile = "";
continue;
}
try {
fldr.mkdirs();
}
catch (Exception ex) {
// Error in folder creation...
System.out.println(ls + "createListRunCount() Method Error! Unable to create path!" + ls
+ "[" + fldr.getAbsolutePath() + "]" + ls + "Please try again..." + ls);
destinationFile = "";
continue;
}
destinationFile = fldr.getAbsolutePath() + "\\p01-runs.txt";
}
}
ArrayList<Integer> list = new ArrayList<>();
/* Prepare for writing to the destination file.
Try With Resourses is use here to auto-close
the writer. */
try (PrintWriter printWriter = new PrintWriter(destinationFile)) {
System.out.println(ls + "Reading file...");
/**
* Reads lines from the file, removes spaces in the line converts
* the string to an integer and adds the integer to the List.
*/
String temp = null;
/* Prepare for writing to the destination file.
Try With Resourses is use here to auto-close
the reader. */
try (Scanner reader = new Scanner(file)) {
while (reader.hasNextLine()) {
temp = reader.nextLine().replaceAll("\\s+", "");
/* Make sure the line isn't blank and that the
line actually contains no alpha characters.
The regular expression: "\\d+" is used for
this with the String#matches() method. */
if (temp.equals("") || !temp.matches("\\d+")) {
continue;
}
int num = Integer.parseInt(temp);
list.add(num);
}
// PLACE YOUR WRITER PROCESSING CODE HERE
}
catch (FileNotFoundException ex) {
Logger.getLogger("createListRunCount() Method Error!").log(Level.SEVERE, null, ex);
}
}
catch (FileNotFoundException ex) {
Logger.getLogger("createListRunCount() Method Error!").log(Level.SEVERE, null, ex);
}
/* return the path and file name of the
destination file auto-created. */
return destinationFile;
}
}

How to read inputs from a text file and put those inputs into an ArrayList in Java?

so I want to read in a text file with a bunch of inputs containing strings like this:
abc456
mnjk452
aaliee23345
poitt78
I want to put each of these inputs into an array list and pass that arraylist through one of my methods. How would I go about doing so? Currently in my code, I'm trying to see if i can simply print out what's in my arraylist. Here is what i have in my main:
public static void main(String[] args) {
if(args.length < 1) {
System.out.println("Give me a file!");
}
String fname = args[0];
ArrayList<String> coordinates = new ArrayList<String>();
Scanner grid = new Scanner(fname);
while(grid.hasNext()) {
coordinates.add(grid.nextLine());
}
for(String coordinate : coordinates) {
System.out.println(coordinate);
}
}
How about this:
Path path = Paths.get(args[0]);
List<String> coordinates = Files.readAllLines(path);
System.out.print(coordinates); // [abc456, mnjk452, aaliee23345, poitt78]
Same can be accomplished with the Scanner:
Path path = Paths.get(args[0]);
List<String> result = new ArrayList<>();
Scanner sc = new Scanner(path);
while (sc.hasNextLine()) {
String line = sc.nextLine();
result.add(line);
}
System.out.print(result); // [abc456, mnjk452, aaliee23345, poitt78]
Do not forget to pass your arguments when you run your application (either in your IDE or command line)!
When reading from a file you need to create a File object that you give to the Scanner object. Also you should control your while loop based on grid.hasNextLine() since you are grabbing line by line. Lastly when running the program from terminal you should be doing the following
java "name of your class with main" "file name"
Which will pass that file in as a parameter to args[0]
try
{
Scanner grid = new Scanner(new File(fname));
while(grid.hasNextLine())
{
coordinates.add(grid.nextLine());
}
}catch(FileNotFoundException e)
{
System.err.println("File " + fname + " does not exist/could not be found");
e.printStackTrace();
}

Java: Methods, Files, and Arrays

I'm supposed to be coding an app that can read names from a hardcoded text file, save them as a string array, then write those names in a different text file but sorted. I believe I have the first two parts down but I'm confused on how to sort the names then write them into a new file.
These is the actual problem I'm working on:
"Take an input file with 10 names in it (hard coded). Write a program to read the file, save the names in a String array and write into a different file names in sorted order. Use Methods appropriately."
BTW I'm a rookie coder, this is what I have so far.
public static void main(String[] args) throws FileNotFoundException {
// TODO code application logic here
readFile();
saveStringArray();
}
public static void readFile() {
File file = new File("/Users/nicoladaaboul/Desktop/Programming/C++, "
+ "HTML5, Java, PHP/Java/Question2/names.txt");
try {
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String i = sc.next();
}
sc.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void saveStringArray() throws FileNotFoundException {
String token1 = "";
Scanner inFile1 = new Scanner(new File("names.txt")).useDelimiter(",\\s*");
List<String> temps = new ArrayList<String>();
while (inFile1.hasNext()) {
token1 = inFile1.next();
temps.add(token1);
}
inFile1.close();
String[] tempsArray = temps.toArray(new String[0]);
Arrays.sort(tempsArray);
for (String s : tempsArray) {
System.out.println(s);
}
}
public static void sortingNames() {
}
public static void writingFile() throws FileNotFoundException {
PrintWriter writer = new PrintWriter("sortedNames.txt");
writer.close();
}
Its important that you break your problem down into instructions.
1. You need to read the file you can use bufferedReader(code below).
2. Create an array(or arraylist) to store your string values.
3. Then as you read each line, store these values in the array.
4. When finished reading the file you then would pass this array to a function that would sort it(Why does my sorting loop seem to append an element where it shouldn't?).
5. Once sorted you simply write this array, to a file.
BufferedReader br = new BufferReader(new FileReader("name.txt"));
int count = 0;
String line;
String[] names = new String[100];
while((line = br.nextLine()) != null){
names[count] = line;
count++;
}

Categories

Resources