I'm creating an application which will get the all the rpms in the table, well when I want to append it to a textfile something wrong, Please see the code below.
public class rpms(){
public static void main(String[] args) {
URLget rpms = new URLget();
try {
getTdSibling(sendGetRequest(URL).toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void getTdSibling(String sourceTd) throws FileNotFoundException, UnsupportedEncodingException {
String fragment = sourceTd;
Document doc = Jsoup.parseBodyFragment(fragment);
for (Element table : doc.select("table")) {
for (Element row : table.select("tr")) {
Elements lines = row.select("td");
String linesToStr = lines.text();
String[] linestoStrArray = linesToStr.split("\n");
for (String line : linestoStrArray)
if (!line.contains("Outdated")){
//System.out.println(""+line);// display the rpms that do not have outdated
for (int i = 0; i < lines.size(); i++) {
if(!lines.eq(i).text().toString().equals(" ")){
splitStr(lines.eq(i).text().toString());
}
}
}
}
}
}
public static void splitStr(String str1) throws FileNotFoundException, UnsupportedEncodingException{
ArrayList<String> outputContent = new ArrayList<String>();
String[] split1 = str1.split(" ");
for (int i = 0; i < split1.length; i++) {
if(fileExplode(split1[i])){
System.out.println(split1[i]);
outputContent.add(split1[i]);
}
}
copyFile(outputContent);
}
public static void copyFile(ArrayList<String> fileCon1) throws FileNotFoundException, UnsupportedEncodingException{
PrintWriter writer1 = new PrintWriter("C:\\Users\\usersb\\Downloads\\rpms\\newrpms.txt", "UTF-8");
for(int i = 0 ; i < fileCon1.size() ; i++){
writer1.println(fileCon1.get(i));
}
System.out.println("updated newrpms.txt");
writer1.close();
}
public static boolean fileExplode(String str1) {
boolean hasRPM = false;
String[] split1 = str1.replace(".", " ").split(" ");
for (int i = 0; i < split1.length; i++) {
if ((i + 1) == split1.length) {
if (split1[i].endsWith("rpm")
|| (split1[i].length() > 2 && split1[i].charAt(0) == '.' && split1[i].charAt(1) == 'r'
&& split1[i].charAt(2) == 'p' && split1[i]
.charAt(3) == 'm')) {
hasRPM = true;
}
break;
}
}
return hasRPM;
}
}
After I execute the code. The file is empty. what should I do to get the same output displayed in this statemen System.out.println(split1[i]);
Add writer1.flush(); befor you close the PrintWriter writer1.close();
or
This is a working code for write a String value to text file, Try this in your copyFile method
PrintWriter out = null;
try {
out = new PrintWriter("C:\\45.txt"); //path where you want to create your file
} catch (FileNotFoundException ex) {
}
StringBuffer writesb = null;
writesb = new StringBuffer();
//append text
writesb.append("w");
//Line Spacer.writes to a new line
writesb.append(System.getProperty("line.separator"));
writesb.append("e");
out.print(writesb.toString());
out.flush();
out.close();
Related
Exception in thread "main" java.lang.NumberFormatException: For input string: "zwitterionic"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at longestCompound.shortestStringPrefix(longestCompound.java:31)
at longestCompound.main(longestCompound.java:10)
Process finished with exit code 1
public static String readFile() {
String data = null;
try {
File myObj = new File("/Desktop/Github/java-project/Conditional-statement/src/words.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
data = myReader.nextLine();
//System.out.println(data);
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
return data;
}
public static String shortestStringPrefix() {
String[] str = new String[Integer.parseInt(readFile())];
String longestComp = "";
if (str == null || str.length == 0) return longestComp;
int i = 0;
for (char c : str[0].toCharArray()) {
for (int j = 0; j < str.length; j++) {
if (i >= str[j].length() || c != str[j].charAt(i)) return longestComp;
}
longestComp += c;
i++;
}
System.out.println(longestComp);
return longestComp;
}
I did not want to repeat the other question, I solved a problem in which I post the most common word in the text, but I have a problem, it does not work if I have more blank lines, how can I solve it?
I tried other ways of stackoverflow, but failed.
This is my code.
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
Map < String, Integer > map = new LinkedHashMap < String, Integer > ();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(System.in));
String currentLine = reader.readLine();
while (currentLine != null) {
String[] input = currentLine.replaceAll("[^a-zA-Z-\"\\n\\n\", \"\\n\"]", " ").toLowerCase().split(" ");
for (int i = 0; i < input.length; i++) {
if (map.containsKey(input[i])) {
int count = map.get(input[i]);
map.put(input[i], count + 1);
} else {
map.put(input[i], 1);
}
}
currentLine = reader.readLine();
}
String mostRepeatedWord = null;
int count = 0;
for (Map.Entry < String, Integer > m: map.entrySet()) {
if (m.getValue() > count) {
mostRepeatedWord = m.getKey();
count = m.getValue();
} else if (m.getValue() == count) {
String key = m.getKey();
if (key.compareTo(mostRepeatedWord) < 0) {
mostRepeatedWord = key;
}
}
}
System.out.println(mostRepeatedWord);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Modify your for loop so that you're not adding to your map on a blank line.
for (int i = 0; i < input.length; i++) {
// Skip the blank lines
if (!input[i].trim().equals("")) {
if (map.containsKey(input[i])) {
int count = map.get(input[i]);
map.put(input[i], count + 1);
} else {
map.put(input[i], 1);
}
}
}
I have a simple java class that uses System.err.println to debug the code as it executes. the purpuse of the class is to find the maximum pairwise product of a given numbers.
following is the code and output.
public class MaxPairwiseProduct {
private static boolean enableLog = true;
static long getMaxPairwiseProductFast(int[] numbers) {
long max_product = 0;
int n = numbers.length;
int firstMaxInt = -1;
int secondMaxInt = -1;
int firstMaxIndex = 0;
int secondMaxIndex = 0;
loge("firstMax initialized :" + firstMaxInt);
loge("secondMax initialized :"+ secondMaxInt);
loge("***********************************************");
for (int firstPassIndex = 1; firstPassIndex < n; firstPassIndex++) {
loge("firstpass : Number " +firstPassIndex);
if (numbers[firstPassIndex] > firstMaxInt )
{
loge("\t firstpass : Found max " +numbers[firstPassIndex]);
firstMaxInt = numbers[firstPassIndex] ;
firstMaxIndex = firstPassIndex ;
}
}
for (int secondPassIndex = 1; secondPassIndex < n; secondPassIndex++) {
loge("secondPassIndex : Number " +numbers[secondPassIndex]);
if (numbers[secondPassIndex] > secondMaxInt && secondPassIndex != firstMaxIndex )
{
loge("\t firstpass : Found max " +secondPassIndex);
secondMaxInt = numbers[secondPassIndex] ;
secondMaxIndex = secondPassIndex;
}
}
max_product = firstMaxInt * secondMaxInt ;
return max_product;
}
public static void main(String[] args) {
FastScanner scanner = new FastScanner(System.in);
int n = scanner.nextInt();
int[] numbers = new int[n];
for (int i = 0; i < n; i++) {
numbers[i] = scanner.nextInt();
}
System.out.println(getMaxPairwiseProductFast(numbers));
}
private static void loge(String s)
{
if (enableLog == true)
{
System.err.println(s);
}
}
private static void log(String s)
{
if (enableLog == true)
{
System.out.println(s);
}
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(InputStream stream) {
try {
br = new BufferedReader(new
InputStreamReader(stream));
} catch (Exception e) {
e.printStackTrace();
}
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
}
the output is (from the output window in Netbeans):
It is clear that the output messages is not in the intended order.
It appears to me as if the program execute in multi-thread.
what is the error in my code and why it output like this ?
I found the answer here
Delay in running thread due to system.out.println statement
a stackOverflow member guided me to this.
basically , changing the loge method to the following fixed the issue.
private static void loge(String s)
{
if (enableLog == true)
{
System.err.println(s);
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(MaxPairwiseProduct.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
I have a table in database with 5 columns. In CSV file I have data like below. How to process it into Oracle database by elimating empty columns (because CSV file contains 6 columns, it will mismatch in database columns having 5 columns).
111, ,John,2000, ,US
222, ,Alle,3000, ,China
333, ,Kite,4000,LCD,IND
444, ,King,5000,LED,Aust
package com.java;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.List;
import java.util.Vector;
public class Test3
{
public static void main(String[] args)
{
try
{
int commas = 0;
List data = new Vector();
List columnCount = new Vector();
String[] cols = null;
String[] strArray = null;
String file = "D:/temp/CSV/data.csv";
BufferedReader br = new BufferedReader(new FileReader(file));
String line = br.readLine();
do
{
commas = 0;
cols = line.split(",");
strArray = new String[cols.length];
int i=0;
for (String element : cols)
{
if (!isBlank(element))
{
strArray[i] = element;
i++;
}
}
int newFile = line.length();
for(int k = 0; k < newFile; k ++ )
{
char eachChar = line.charAt(k);
if(eachChar == ',')
{
commas ++;
}
}
data.add(strArray);
line = br.readLine();
}
while (line != null);
Vector columns = new Vector(commas + 1);
for(int i = 0; i < commas +1 ; i ++ )
{
columns.add("" + i);
}
} catch (Exception e) {
}
}
public static boolean isBlank(String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0)
{
return true;
}
for (int i = 0; i < strLen; i++)
{
if ((Character.isWhitespace(str.charAt(i)) == false)) {
return false;
}
}
return true;
}
}
You can use a util method to check if it is empty string or not.
public static boolean isBlank(String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if ((Character.isWhitespace(str.charAt(i)) == false)) {
return false;
}
}
return true;
}
and use it in your reader like below
Scanner s = null;
try {
s = new Scanner(new File("D:/sri/Test.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (s.hasNextLine()) {
String[] line = s.nextLine().split(",");
for (String element : line) {
if (!isBlank(element))
System.out.println(element);
}
}
I am trying to develop a basic java program to compare two huge text files and print non matching records .i.e. similar to minus function in SQL. but I am not getting the expected results because all the records are getting printed even though both files are same. Also suggest me whether this approach is performance efficient for comparing two huge text files.
import java.io.*;
public class CompareTwoFiles {
static int count1 = 0 ;
static int count2 = 0 ;
static String arrayLines1[] = new String[countLines("\\Files_Comparison\\File1.txt")];
static String arrayLines2[] = new String[countLines("\\Files_Comparison\\File2.txt")];
public static void main(String args[]){
findDifference("\\Files_Comparison\\File1.txt","\\Files_Comparison\\File2.txt");
displayRecords();
}
public static int countLines(String File){
int lineCount = 0;
try {
BufferedReader br = new BufferedReader(new FileReader(File));
while ((br.readLine()) != null) {
lineCount++;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return lineCount;
}
public static void findDifference(String File1, String File2){
String contents1 = null;
String contents2 = null;
try
{
FileReader file1 = new FileReader(File1);
FileReader file2 = new FileReader(File2);
BufferedReader buf1 = new BufferedReader(file1);
BufferedReader buf2 = new BufferedReader(file2);
while ((contents1 = buf1.readLine()) != null)
{
arrayLines1[count1] = contents1 ;
count1++;
}
while ((contents2 = buf2.readLine()) != null)
{
arrayLines2[count2] = contents2 ;
count2++;
}
}catch (Exception e){
e.printStackTrace();
}
}
public static void displayRecords() {
for (int i = 0 ; i < arrayLines1.length ; i++) {
String a = arrayLines1[i];
for (int j = 0; j < arrayLines2.length; j++){
String b = arrayLines2[j];
boolean result = a.contains(b);
if(result == false){
System.out.println(a);
}
}
}
}
}
Based upon your explanation you do not need embedded loops
consider
public static void displayRecords() {
for (int i = 0 ; i < arrayLines1.length && i < arrayLines2.length; i++)
{
String a = arrayLines1[i];
String b = arrayLines2[i];
if(!a.contains(b){
System.out.println(a);
}
}
For the performance wise, you should try to match the size of the files. If the sizes(in bytes) are exactly the same, you might not need to compare them.