Comparing two file contents in java and save it another file - java

this is my code, im trying to compare two .csv files and match them and save the common pain in another file. How do i do it?
This is the cotnent of item_no.csv file
1
2
3
4
5
This is the content of item_desc.csv file
1,chocolate,100
2,biscuit,20
3,candy,10
4,lollipop,5
5,colddrink,50
6,sandwitch,70
EDIT This is the expected output:
1,chocolate,100
2,biscuit,20
3,candy,10
4,lollipop,5
5,colddrink,50
This is my code:
package fuu;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import com.sun.org.apache.xerces.internal.impl.xpath.regex.ParseException;
public class Demo {
public static void main(String[] args) throws ParseException, IOException {
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new FileReader("/home/yotta/eclipse/workspace/Test/WebContent/doc/item_no.csv"));
BufferedReader br1 = new BufferedReader(new FileReader("/home/yotta/eclipse/workspace/Test/WebContent/doc/item_desc.csv"));
String line = null;
String line1 = null;
String line2 = null;
String[] str=null;
String[] str1=null;
try {
while((line = br.readLine())!=null){
str = line.split(",");
System.out.println(str[0]);
}
while((line1 = br1.readLine())!=null){
str1 = line1.split(",");
System.out.println(str1[0]+" "+str1[1]+" "+str1[2]);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

You could separate the different steps.
public class Demo {
public static void main(String[] args) throws IOException {
Map<String, String> descMap = new HashMap<>();
String line;
// read all item descriptions
try (BufferedReader br1 = new BufferedReader(new FileReader("item_desc.csv"))) {
while ((line = br1.readLine()) != null) {
int itemNbrSeparator = line.indexOf(',');
String itemNbr = line.substring(0, itemNbrSeparator);
descMap.put(itemNbr, line);
}
}
List<String> matched = new ArrayList<>();
// read the item numbers and store each matched
try (BufferedReader br = new BufferedReader(new FileReader("item_no.csv"))) {
while ((line = br.readLine()) != null) {
if (descMap.containsKey(line)) {
System.out.println(descMap.get(line));
matched.add(descMap.get(line));
}
}
}
// output all matched
Path outFile = Paths.get("item_match.csv");
Files.write(outFile, matched, Charset.defaultCharset(), new LinkOption[0]);
}
}

One way is this
List<String> lines1 = new ArrayList<String>();
while ((line = br.readLine()) != null) {
str = line.split(",");
lines1.add(line);
System.out.println(str[0]);
}
List<String> lines2 = new ArrayList<String>();
while ((line = br1.readLine()) != null) {
str = line.split(",");
System.out.println(str[0]);
if(lines1.contains(str[0])){
lines2.add(line);
}
}
for (String l : lines1) {
System.out.println(l);
}

Related

Get range of lines in file

i would like to save in a string multiple lines from reading file, eg: I am reading one file.txt with the following content:
def var x as int.
def var y as char.
procedure something:
//here some content
end.
I would like to catch content between "procedure" and "end".
public static void main(String[] args) {
String piContent = "";
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
String line;
while ((line = br.readLine()) != null) {
if(line.contains("procedure")){
piContent = line;
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
I appreciate any help.
final StringBuilder sb = new StringBuilder();
try (final BufferedReader br = Files.newBufferedReader(file.toPath(), StandardCharsets.UTF_8)) {
String line;
boolean rememberStuff = false;
while ((line = br.readLine()) != null) {
if (line.startsWith("procedure ")) {
rememberStuff = true;
} else if (line.startsWith("end.")) {
rememberStuff = false;
} else if (rememberStuff) {
sb.append(line).append('\n');
}
}
} catch (IOException e) {
e.printStackTrace();
}
System.err.println("Lines found between procedure and end:");
System.err.println(sb);
public static String getContentFromFile(Path file) throws IOException {
StringBuilder buf = new StringBuilder();
boolean add = false;
for (String line : Files.readAllLines(file)) {
if ("end.".equalsIgnoreCase(line.trim()))
break;
if (add)
buf.append(line).append(System.lineSeparator());
else if ("procedure something:".equalsIgnoreCase(line.trim()))
add = true;
}
return buf.toString();
}

multiple words replace in txt file using java

I need to replace multiple words in txt file using java. This program only replacing the only one word, in whole file.
import java.io.*;
public class MultiReplace
{
public static void main(String args[])
{
try
{
File file = new File("file.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "", oldtext = "";
while((line = reader.readLine()) != null)
{
oldtext += line + "\r\n";
}
reader.close();
String newtext = oldtext.replaceAll("india", "freedom");
FileWriter writer = new FileWriter("file.txt");
writer.write(newtext);writer.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
Try this:
import java.io.*;
public class MultiReplace
{
public static void main(String args[])
{
try
{
File file = new File("file.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "", oldtext = "";
while((line = reader.readLine()) != null)
{
// Replace in the line and append
line = line.replaceAll("india", "freedom");
oldtext += line + "\r\n";
}
reader.close();
FileWriter writer = new FileWriter("file.txt");
writer.write(newtext);
writer.flush();
writer.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
Refer this to understand why your version is not working.
Your solution is correct!! I ran your program as is and it is able to replace all the india with freedom in the text file

Need a word list from the internet

Hello I'm creating a HangMan game and I want the array list of words to come from the internet. Its not initializing for me. Can anyone help? This is the code.
public String getaword()
{
try
{
URL url = new URL ("http://dictionary-thesaurus.com/wordlists/Adjectives%28929%29.txt");
//URLConnection urlConnection = (URLConnection)url.openConnection();
//inStream = new InputStreamReader(urlConnection.getInputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str=null;
ArrayList<String> lines = new ArrayList<String>();
while((str = in.readLine()) != null)
{
lines.add(str);
words = lines.toArray(new String[lines.size()]);
}
}
catch (Exception e)
{
e.getStackTrace();
}
Random r = new Random();
int num;
num = r.nextInt(words.length);
return words[num];
}
Try this.
public static void main(String[] args) {
ArrayList<String> lines = new ArrayList<String>();
try {
URL url = new URL ("http://dictionary-thesaurus.com/wordlists/Adjectives(929).txt");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str = null;
while((str = in.readLine()) != null) {
lines.add(str);
}
}
catch (Exception e) {
e.printStackTrace();
}
System.out.println(lines);
}

Public string - cannot be resolved

Error at
bw.write(dataString);
How can i fix this?
dataString cannot be resolved to a variable.
public class test {
public static void main(String[] args){
ArrayList<String> data = new ArrayList<String>();
try (BufferedReader br = new BufferedReader(new FileReader("src/test.txt"))) {
String CurrLine;
while((CurrLine = br.readLine()) != null) {
data.add(CurrLine);
}
String[] dataArray = new String[data.size()];
String dataString = Arrays.toString(dataArray);
String[] client = dataString.split("<::>");
Integer nameId = Arrays.binarySearch(client, "Test");
Integer versId = nameId + 1;
System.out.println(client[nameId] + "\n" + client[versId]);
} catch(FileNotFoundException ex) {
System.out.println("FNFE");
} catch(IOException ex) {
System.out.println("IOE");
}
try{
File file = new File("src/test.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(dataString);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
DeclaredataString outside of the try and catch block... Thats all. ;) If you declare it inside a loop or in this case your try catch block, its lifecycle is limited to it.
Like this:
String dataString = null;
and inside the try-catch block:
dataString = Arrays.toString(dataArray);
dataString is out of scope in the try block.
Perhaps add dataString as an instance variable at the top of your class.
public class test {
private String dataString = null;
public static void main(String[] args){
ArrayList<String> data = new ArrayList<String>();
try (BufferedReader br = new BufferedReader(new FileReader("src/test.txt"))) {
String CurrLine;
while((CurrLine = br.readLine()) != null) {
data.add(CurrLine);
}
String[] dataArray = new String[data.size()];
dataString = Arrays.toString(dataArray);
...
The dataString variable's scope is limited to the first try-catch block. Change its declaration as following,
public static void main(String[] args){
ArrayList<String> data = new ArrayList<String>();
String dataString = null;
try (BufferedReader br = new BufferedReader(new FileReader("src/test.txt"))) {
String CurrLine;
while((CurrLine = br.readLine()) != null) {
data.add(CurrLine);
}
String[] dataArray = new String[data.size()];
dataString = Arrays.toString(dataArray);
String[] client = dataString.split("<::>");
Integer nameId = Arrays.binarySearch(client, "Test");
Integer versId = nameId + 1;
System.out.println(client[nameId] + "\n" + client[versId]);
} catch(FileNotFoundException ex) {
System.out.println("FNFE");
} catch(IOException ex) {
System.out.println("IOE");
}
try{
File file = new File("src/test.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(dataString);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}

How can I read äöüß in java?

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
public class Test {
List<String> knownWordsArrayList = new ArrayList<String>();
List<String> wordsArrayList = new ArrayList<String>();
List<String> newWordsArrayList = new ArrayList<String>();
String toFile = "";
public void readKnownWordsFile() {
try {
FileInputStream fstream2 = new FileInputStream("knownWords.txt");
BufferedReader br2 = new BufferedReader(new InputStreamReader(fstream2, "UTF-8"));
String strLine;
while ((strLine = br2.readLine()) != null) {
knownWordsArrayList.add(strLine.toLowerCase());
}
HashSet h = new HashSet(knownWordsArrayList);
// h.removeAll(knownWordsArrayList);
knownWordsArrayList = new ArrayList<String>(h);
// for (int i = 0; i < knownWordsArrayList.size(); i++) {
// System.out.println(knownWordsArrayList.get(i));
// }
} catch (Exception e) {
// TODO: handle exception
}
}
public void readFile() {
try {
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("Smallville 4x02.de.srt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
String numberedLineRemoved = "";
String strippedInput = "";
String[] words;
String trimmedString = "";
String temp = "";
// Read File Line By Line
while ((strLine = br.readLine()) != null) {
temp = strLine.toLowerCase();
// Print the content on the console
numberedLineRemoved = numberedLine(temp);
strippedInput = numberedLineRemoved.replaceAll("\\p{Punct}", "");
if ((strippedInput.trim().length() != 0) || (!strippedInput.contains("")) || (strippedInput.contains(" "))) {
words = strippedInput.split("\\s+");
for (int i = 0; i < words.length; i++) {
if (words[i].trim().length() != 0) {
wordsArrayList.add(words[i]);
}
}
}
}
HashSet h = new HashSet(wordsArrayList);
h.removeAll(knownWordsArrayList);
newWordsArrayList = new ArrayList<String>(h);
// HashSet h = new HashSet(wordsArrayList);
// wordsArrayList.clear();
// newWordsArrayList.addAll(h);
for (int i = 0; i < newWordsArrayList.size(); i++) {
toFile = newWordsArrayList.get(i) + ".\n";
// System.out.println(newWordsArrayList.get(i) + ".");
System.out.println();
}
System.out.println(newWordsArrayList.size());
// Close the input stream
in.close();
} catch (Exception e) {// Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
public String numberedLine(String string) {
if (string.matches(".*\\d.*")) {
return "";
} else {
return string;
}
}
public void writeToFile() {
try {
// Create file
FileWriter fstream = new FileWriter("out.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write(toFile);
// Close the output stream
out.close();
} catch (Exception e) {// Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
public static void main(String[] args) {
Test test = new Test();
test.readKnownWordsFile();
test.readFile();
test.writeToFile();
}
}
How can I read äöüß from file?
Would the string.toLowercase() handle these properly as well?
And when I go to print words containing any of äöüß, how can I print the word properly?
When I print to console I get
Außerdem
weiß
for Außerdem
weiß
How can I fix this?
I tried:
BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
But now I'm getting aufkl?ren instead of aufklären and its messing up in other places as well.
Updated the code to see if it would print on the file properly, but I'm just getting one in the file.
You need to read files using the charset which was used to create the file. If you're on a windows machine, that's probably cp1252. So:
BufferedReader br = new BufferedReader(new InputStreamReader(in, "Cp1252"));
If that doesn't work, most text editors are capable of telling you what encoding is used for a given document.

Categories

Resources