File Comparer doesn't write result to file - java

Hiho guys,
I am writing an easy application, which should open two .txt files, take first line of the first file and then iterate through every line of second file. If it finds the same String in second file, then it should write this string to outputfile.txt with nextline. After the loop over the second file is done, it should take the second line from the first line and search for the same String and if finds then writes it with nextline.
I've tried it by myself but it does nothing, I mean it doesn't put any text into outputfile.txt, even if I am sure that there are same words.
package com.company;
import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
String sourceFileName = "C:\\Users\\Maciej\\IdeaProjects\\spring5webapp\\FileTextChecker\\src\\com\\company\\BootfileRO.txt";
String comparingFileName = "C:\\Users\\Maciej\\IdeaProjects\\spring5webapp\\FileTextChecker\\src\\com\\company\\BootfileSK.txt";
String outputFileName = "C:\\Users\\Maciej\\IdeaProjects\\spring5webapp\\FileTextChecker\\src\\com\\company\\output.txt";
System.out.println("Starting ... ");
File file1 = new File(sourceFileName);
File file2 = new File(comparingFileName);
PrintWriter file3 = new PrintWriter(outputFileName);
String line1 = "";
String line2 = "";
Scanner scan1 = new Scanner(file1);
Scanner scan2 = new Scanner(file2);
while(scan1.hasNextLine()){
line1 = scan1.nextLine();
while(scan2.hasNextLine()){
line2 = scan2.nextLine();
if(line1.equals(line2)){
file3.println(line1);
}
else{
continue;
}
}
}
file3.close();
// Comparer comparer = new Comparer(sourceFileName, comparingFileName, oFN);
// comparer.compare();
// CompareByScanner compareBYScanner = new CompareByScanner(sourceFileName, comparingFileName, outputFileName);
// compareBYScanner.compare();
}
}
To be honest, it looks like the "equals" function can't find the same strings, but I am sure they exists.

The problem here is that scan2 never resets, therefore after comparing the first line of file1, scan2.hasNextLine() will return false and therefore does not compare any further lines. Instead, set scan2 equal to a new Scanner at every iteration of the scan1 loop. This will set it to the start of the file. Then, after scanning the file, close the Scanner. New code:
package test;
import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;
public class TestMain {
public static void main(String[] args) throws IOException {
String sourceFileName = "src/output/compare1.txt";
String comparingFileName = "src/output/compare2.txt";
String outputFileName = "src/output/output.txt";
System.out.println("Starting ... ");
File file1 = new File(sourceFileName);
File file2 = new File(comparingFileName);
PrintWriter file3 = new PrintWriter(outputFileName);
String line1 = "";
String line2 = "";
Scanner scan1 = new Scanner(file1);
Scanner scan2;
while(scan1.hasNextLine()){
line1 = scan1.nextLine();
scan2 = new Scanner(file2);
while(scan2.hasNextLine()){
line2 = scan2.nextLine();
System.out.println("Line 1: " + line1 + "\n" + "Line 2: " + line2);
if(line1.equals(line2)){
file3.println(line1);
}
}
scan2.close();
}
file3.close();
// Comparer comparer = new Comparer(sourceFileName, comparingFileName, oFN);
// comparer.compare();
// CompareByScanner compareBYScanner = new CompareByScanner(sourceFileName,
comparingFileName, outputFileName);
// compareBYScanner.compare();
}
}

Related

How to add a column to CSV which consists of data in Java

Can we add a new column to CSV as the last column which already has let's say 3 columns with some data in it? So this new one will be added later as 4th column moreover for every row it should have random numbers.
Example,
Id Name Address Calculated
1 John U.K. 341679
2 Vj Aus 467123
3 Scott U.S. 844257
From what I understand this will require first to read csv, for loop may be to iterate to the last column and then add a new calculated column i.e Write to csv. And to add values may be the Random class of Java. But how exactly can this be done is the real question. Like a sample code would be helpful.
Code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Demo1 {
public static void main(String[] args) throws IOException {
String csvFile = "C:\\MyData\\Input.csv";
String line = "";
String cvsSplitBy = ",";
String newColumn = "";
List<String> aobj = new ArrayList<String>();
/* Code to read Csv file and split */
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null)
{
String[] csvData = line.split(cvsSplitBy);
int arrayLength = csvData.length;
}
}
/* Code to generate random number */
String CHARS = "1234567890";
StringBuilder random = new StringBuilder();
Random rnd = new Random();
while (random.length() < 18) { // length of the random string.
int index = (int) (rnd.nextFloat() * CHARS.length());
random.append(CHARS.charAt(index));
}
String finaldata = random.toString();
}
}
Great, so based on the code you provide, this could look like the following
(just to give you the idea - I write it here on the fly without testing...)
:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Demo1 {
//moved your random generator here
public static String getRandomNumber() {
/* Code to generate random number */
String CHARS = "1234567890";
StringBuilder random = new StringBuilder();
Random rnd = new Random();
while (random.length() < 18) { // length of the random string.
int index = (int) (rnd.nextFloat() * CHARS.length());
random.append(CHARS.charAt(index));
}
String finaldata = random.toString();
return finaldata;
}
public static void main(String[] args) throws IOException {
String csvFile = "C:\\MyData\\Input.csv";
String temporaryCsvFile = "C:\\MyData\\Output_temp.csv";
String line = "";
String cvsSplitBy = ",";
String newColumn = "";
List<String> aobj = new ArrayList<String>();
/* Code to read Csv file and split */
BufferedWriter writer = new BufferedWriter(new FileWriter(
temporaryCsvFile));
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null)
{
//String[] csvData = line.split(cvsSplitBy);
//int arrayLength = csvData.length;
//actually you don't even need to split anything
String newFileLine = line + cvsSplitBy + getRandomNumber();
// ... We call newLine to insert a newline character.
writer.write(newFileLine);
writer.newLine();
}
}
writer.close();
//Now delete the old file and rename the new file
//I'll leave this to you
}
}
Based on #Plirkee sample code and his help I made a final working code. Sharing it here so that it might be useful for someone with a similar requirement.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
public class Demo1 {
public static String getRandomNumber() {
String CHARS = "1234567890";
StringBuilder random = new StringBuilder();
Random rnd = new Random();
while (random.length() < 18) // length of the random string.
{
int index = (int) (rnd.nextFloat() * CHARS.length());
random.append(CHARS.charAt(index));
}
String finaldata = random.toString();
return finaldata;
}
public static void main(String[] args) throws IOException {
File sourceCsvFile = null;
File finalCsvFile = null;
// String sourceCsvFileName = "";
sourceCsvFile = new File("C:\\MyData\\Input.csv");
finalCsvFile = new File("C:\\MyData\\Input_1.csv");
String line = "";
String cvsSplitBy = ",";
BufferedWriter writer = new BufferedWriter(new FileWriter(finalCsvFile));
try (BufferedReader br = new BufferedReader(new FileReader(sourceCsvFile))) // read the actual Source downloaded csv file
{
line = br.readLine(); // read only first line
String newFileLine = line + cvsSplitBy + "HashValue"; // append "," and new column <HashValue>
writer.write(newFileLine); // will be written as first line in new csv
writer.newLine(); // go to next line for writing next lines
while ((line = br.readLine()) != null) // this loop to write data for all lines except headers
{
newFileLine = line + cvsSplitBy + getRandomNumber(); // will add random numbers for each row
writer.write(newFileLine);
writer.newLine();
}
}
writer.close();
if(finalCsvFile.exists() && finalCsvFile.length() > 0)
{
System.out.println("New File with HashValue column created...");
if(sourceCsvFile.delete())
{
System.out.println("Old File deleted successfully...");
}
else
{
System.out.println("Failed to delete the Old file...");
}
}
else if (!finalCsvFile.exists())
{
System.out.println("New File with HashValue column not created...");
}
}
}

Write to file line by line

So my input file has some sentences, and i want to reverse the words in each sentence and keep the same order of sentences. I then need to print to a file. my problem is that my output file is only printing my last sentence, reversed.
import java.util.*;
import java.io.*;
public class Reverser { //constructor Scanner sc = null ; public
Reverser(File file)throws FileNotFoundException, IOException {
sc = new Scanner (file); }
public void reverseLines(File outpr)throws FileNotFoundException, IOExeption{
//PrintWriter pw = new PrintWriter(outpr);
while(sc.hasNextLine()){
String sentence = sc.nextLine();
String[] words = sentence.split(" ");
ArrayList<String> wordsarraylist = new ArrayList<String>(Arrays.asList(words));
Collections.reverse(wordsarraylist);
FileWriter fw = new FileWriter(outpr);
BufferedWriter bw = new BufferedWriter(fw);
for(String str: wordsarraylist) {
bw.write(str + " ");
bw.newLine();
bw.close();
}
} }
}
That's because each time you loop, you reopen the file in overwrite mode.
Open the file before you start looping instead.
Don't use the append option here, it'll just make you open/close the file needlessly.

how to read and write the answer in file i/o

i have this code i am working on i can read from file ,but i cant save the answer to my txt file .also how do i recall to do other operation on same number .i need a tips on how to do that.
package x;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class x {
public static void main(String args[]) throws FileNotFoundException {
//creating File instance to reference text file in Java
File text = new File("C:\\Users\\user\\Desktop\\testScanner.txt");
//Creating Scanner instnace to read File in Java
Scanner scnr = new Scanner(text);
//Reading each line of file using Scanner class
int lineNumber = 1;
while(scnr.hasNextLine()){
String line = scnr.nextLine();
int foo = Integer.parseInt(line);
System.out.println("===================================");
System.out.println("line " + lineNumber + " :" + line);
foo=100*foo;
lineNumber++;
System.out.println(" foo=100*foo " + lineNumber + " :" + foo);
}
}
}
you need to use a filewriter to write a file and filereader to write a file. you also need to import java.io. here is an example code:
import java.io.*;
public class FileRead{
public static void main(String args[])throws IOException{
File file = new File("Hello1.txt");
// creates the file
file.createNewFile();
// creates a FileWriter Object
FileWriter writer = new FileWriter(file);
// Writes the content to the file
writer.write("This\n is\n an\n example\n");
writer.flush();
writer.close();
//Creates a FileReader Object
FileReader fr = new FileReader(file);
char [] a = new char[50];
fr.read(a); // reads the content to the array
for(char c : a)
System.out.print(c); //prints the characters one by one
fr.close();
}
}

Convert text file to camel case then save it

I got the code to remove the spaces in between the words but cant get it to capitalize beginning of each word. can any find what the problem is. it needs to be in camelcase.
Orginal question is - Write a Java program that will read a text file containing unknown lines of strings, turn the whole file into camelCase, and finally save the camelCase into another text file.
package p3;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class CamelCase {
public static void main(String[] args) throws IOException {
String Str = null;
File file = new File("txt.txt");
if(!file.exists()) {
System.out.println("The file does not exist.");
System.exit(0);
}
Scanner filescanner = new Scanner(file);
while (filescanner.hasNext()) {
Str= filescanner.nextLine();
System.out.println(Str);
}
filescanner.close();
char[] characters = Str.toCharArray();
boolean capitalizeWord = true;
for (int i = 0; i < characters.length; i++) {
char c = characters[i];
if (Character.isWhitespace(c)) {
capitalizeWord = true;
}
else if (capitalizeWord) {
capitalizeWord = false;
characters[i] = Character.toUpperCase(c);
}
String capsandnospace = Str.replaceAll("\\s","");
FileWriter fw = new FileWriter("CamelCase.txt");
PrintWriter pw= new PrintWriter("CamelCase.txt");
pw.println(capsandnospace);
pw.close();
}
This code
while (filescanner.hasNext()) {
Str= filescanner.nextLine();
System.out.println(Str);
}
is looping through the file replacing the contents of Str with the current line.
After the loop has finished, the value of Str will be that of the last line.
You need to do your conversion of the string (and writing of the result file) in the loop

How to ask user for an input file name and output file name java?

I am trying to make a program that asks for a program input and output file names, but i am having trouble in making the program, especially for asking the file name for the output file.
Both of these methods will ask the user to enter the appropriate file name and return that name as a String. These methods will be called from the main method. They will return a String so there should be two String variables declared before the methods are called.
This is the part program that reads an input file and creates an output file, but i am having trouble with adding the part of the program that will ask for the file names.
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class WebberProject3 {
private static Map<String, Integer> ticketTypeToPrice = new HashMap<String, Integer>();
private static final String SPACE = " ";
private static final String CURRENCY_SYMBOL = " $";
public static void main(String[] args) {
Scanner scanner = null;
PrintWriter outputFile = null;
DecimalFormat decimalFormat = new DecimalFormat();
decimalFormat.setMinimumFractionDigits(2);
try {
File file = new File("portlandvip2.txt");
scanner = new Scanner(file);
outputFile = new PrintWriter("portland2out.txt");
while (scanner.hasNext()) {
String line = scanner.nextLine();
String[] entriesOnLine = line.split(" ");
// Line with price and ticket type
if(entriesOnLine.length == 2) {
ticketTypeToPrice.put(entriesOnLine[0], Integer.parseInt(entriesOnLine[1]));
StringBuilder sb = new StringBuilder();
sb.append(entriesOnLine[0])
.append(CURRENCY_SYMBOL)
.append(decimalFormat.format(Integer.parseInt(entriesOnLine[1])));
outputFile.println(sb.toString());
} else if (entriesOnLine.length == 4) {
//Line with First Name, Last Name, number of Tickets and Price
int numberOfTickest = Integer.parseInt(entriesOnLine[2]);
int ticketPrice = ticketTypeToPrice.get(entriesOnLine[3]);
int totalPrice = numberOfTickest*ticketPrice;
StringBuilder sb = new StringBuilder();
sb.append(entriesOnLine[0])
.append(SPACE)
.append(entriesOnLine[1])
.append(CURRENCY_SYMBOL)
.append(decimalFormat.format(totalPrice));
outputFile.println(sb.toString());
}
}
} catch (IOException e) {
System.out.println("exception:" + e);
} finally {
scanner.close();
outputFile.close();
}
}
}
In order for this program to work, i need to make 2 different methods with the headers names:
public static String getInputFileName()
public static String getOutputFileName()
Please help, i am a beginner to programming, and i have tried a few different things, but nothing is really working. any help will be really appreciated
This would be an example of something i have tried (I tried this after reading a comment from this post):
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public static void String getInputFileName()
{
System.out.println("Enter filename here : ");
String sWhatever;
Scanner scanIn = new Scanner(System.in);
sWhatever = scanIn.nextLine();
scanIn.close();
System.out.println(sWhatever);
}
}
public class WebberProject3Test1
{
public static void main(String[] args) {
{
private static Map<String, Integer> ticketTypeToPrice = new HashMap<String, Integer>();
private static final String SPACE = " ";
private static final String CURRENCY_SYMBOL = " $";
public static void main(String[] args) {
Scanner scanner = null;
PrintWriter outputFile = null;
DecimalFormat decimalFormat = new DecimalFormat();
decimalFormat.setMinimumFractionDigits(2);
try {
File file = new File("portlandvip2.txt");
scanner = new Scanner(file);
outputFile = new PrintWriter("portland2out.txt");
while (scanner.hasNext()) {
String line = scanner.nextLine();
String[] entriesOnLine = line.split(" ");
// Line with price and ticket type
if(entriesOnLine.length == 2) {
ticketTypeToPrice.put(entriesOnLine[0], Integer.parseInt(entriesOnLine[1]));
StringBuilder sb = new StringBuilder();
sb.append(entriesOnLine[0])
.append(CURRENCY_SYMBOL)
.append(decimalFormat.format(Integer.parseInt(entriesOnLine[1])));
outputFile.println(sb.toString());
} else if (entriesOnLine.length == 4) {
//Line with First Name, Last Name, number of Tickets and Price
int numberOfTickest = Integer.parseInt(entriesOnLine[2]);
int ticketPrice = ticketTypeToPrice.get(entriesOnLine[3]);
int totalPrice = numberOfTickest*ticketPrice;
StringBuilder sb = new StringBuilder();
sb.append(entriesOnLine[0])
.append(SPACE)
.append(entriesOnLine[1])
.append(CURRENCY_SYMBOL)
.append(decimalFormat.format(totalPrice));
outputFile.println(sb.toString());
}
}
} catch (IOException e) {
System.out.println("exception:" + e);
} finally {
scanner.close();
outputFile.close();
}
}
}
}
and i get errors like these:
9 errors found:
File: C:\Users\Eddie\CISS100\WebberProject3Test1.java [line: 10]
Error: Syntax error on tokens, ClassHeader expected instead
File: C:\Users\Eddie\CISS100\WebberProject3Test1.java [line: 12]
Error: Syntax error on token(s), misplaced construct(s)
File: C:\Users\Eddie\CISS100\WebberProject3Test1.java [line: 12]
Error: Syntax error on token ""Enter filename here : "", delete this token
File: C:\Users\Eddie\CISS100\WebberProject3Test1.java [line: 16]
Error: Syntax error on token ";", { expected after this token
File: C:\Users\Eddie\CISS100\WebberProject3Test1.java [line: 26]
Error: Duplicate method main(java.lang.String[]) in type WebberProject3Test1
File: C:\Users\Eddie\CISS100\WebberProject3Test1.java [line: 27]
Error: Syntax error, insert "}" to complete BlockStatements
File: C:\Users\Eddie\CISS100\WebberProject3Test1.java [line: 27]
Error: Syntax error, insert "}" to complete MethodBody
File: C:\Users\Eddie\CISS100\WebberProject3Test1.java [line: 32]
Error: Duplicate method main(java.lang.String[]) in type WebberProject3Test1
File: C:\Users\Eddie\CISS100\WebberProject3Test1.java [line: 74]
Error: Syntax error on token "}", delete this token
If you want to ask a user for input the most common way is to create an instance of the Scanner class with an argument of the System input like so
Scanner userInput = new Scanner(System.in);
You can then call methods of this class that get the next line of text the user types, so your code may look something like this
System.out.println("where to read?");
String in = userInput.nextLine();
System.out.println("where to write?");
String out = userInput.nextLine();
Scanner scanner = new Scanner(new File(in));
PrintWriter outputFile = new PrintWriter(out);
This code allows a user to read and write from the terminal in command line or netbeans/eclipse.
For your compile errors :
Line 10 : public static void String getInputFileName()
Methods/funcitons must be declared inside of the body of a class. So move the entire function
Immediately after your function you have an extra closing curly brace so remove that.
You cannot declare public static void main(String[] args) twice. You especially cannot have a method inside of another so remove the outer public static void main(String[] args) { and the extra opening curly brace that follows.
public static void String getInputFileName() can only have one return type so set it to void since you do not return.
Finally delete the extras closing curly brace at the end.
Your code should look something like this
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class WebberProject3Test1 {
private static Map<String, Integer> ticketTypeToPrice = new HashMap<String, Integer>();
private static final String SPACE = " ";
private static final String CURRENCY_SYMBOL = " $";
public static void getInputFileName() {
System.out.println("Enter filename here : ");
String sWhatever;
Scanner scanIn = new Scanner(System.in);
sWhatever = scanIn.nextLine();
scanIn.close();
System.out.println(sWhatever);
}
public static void main(String[] args) {
Scanner scanner = null;
PrintWriter outputFile = null;
DecimalFormat decimalFormat = new DecimalFormat();
decimalFormat.setMinimumFractionDigits(2);
try {
File file = new File("portlandvip2.txt");
scanner = new Scanner(file);
outputFile = new PrintWriter("portland2out.txt");
while (scanner.hasNext()) {
String line = scanner.nextLine();
String[] entriesOnLine = line.split(" ");
// Line with price and ticket type
if (entriesOnLine.length == 2) {
ticketTypeToPrice.put(entriesOnLine[0], Integer.parseInt(entriesOnLine[1]));
StringBuilder sb = new StringBuilder();
sb.append(entriesOnLine[0])
.append(CURRENCY_SYMBOL)
.append(decimalFormat.format(Integer.parseInt(entriesOnLine[1])));
outputFile.println(sb.toString());
} else if (entriesOnLine.length == 4) {
//Line with First Name, Last Name, number of Tickets and Price
int numberOfTickest = Integer.parseInt(entriesOnLine[2]);
int ticketPrice = ticketTypeToPrice.get(entriesOnLine[3]);
int totalPrice = numberOfTickest * ticketPrice;
StringBuilder sb = new StringBuilder();
sb.append(entriesOnLine[0])
.append(SPACE)
.append(entriesOnLine[1])
.append(CURRENCY_SYMBOL)
.append(decimalFormat.format(totalPrice));
outputFile.println(sb.toString());
}
}
} catch (IOException e) {
System.out.println("exception:" + e);
} finally {
scanner.close();
outputFile.close();
}
}
}
NOTE : This code will now compile, it does not mean that I made it do what you want it to do.
If you need to read the user's input, you can do it for example like this:
System.out.println("Type an input path: ");
Scanner s = new Scanner (System.in);
String input = s.nextLine();
In the input you will have the text, which user wrote.
If you want to ask users to provide file names via typing them in the console, you can use either BufferedReader's readLine or Scanner's nextLine for this. The example for BufferedReader:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ReadConsoleSystem {
public static void main(String[] args) {
System.out.println("Enter filename here : ");
try{
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
String s = bufferRead.readLine();
System.out.println(s);
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
Example for Scanner
import java.util.Scanner;
public class ReadConsoleScanner {
public static void main(String[] args) {
System.out.println("Enter filename here : ");
String sWhatever;
Scanner scanIn = new Scanner(System.in);
sWhatever = scanIn.nextLine();
scanIn.close();
System.out.println(sWhatever);
}
}
Examples taken from this article

Categories