CSVReader and InputStream - java

I have created CSVReader and I am trying to read csv file from assets for that reason I should use InputStream. But my code below does not have inputstream constructor. Could anyone tell me how i could add or change something in code, so I can use inputstream.
public class CSVReader {
private BufferedReader br;
private boolean hasNext = true;
private char separator;
private char quotechar;
private int skipLines;
private boolean linesSkiped;
public int linesCount = 0;
public static final char DEFAULT_SEPARATOR = '|';
public static final char DEFAULT_QUOTE_CHARACTER = '"';
public static final int DEFAULT_SKIP_LINES = 0;
public CSVReader(Reader reader) {
this(reader, DEFAULT_SEPARATOR, DEFAULT_QUOTE_CHARACTER,
DEFAULT_SKIP_LINES);
}
public CSVReader(Reader reader, char separator, char quotechar, int line) {
this.br = new BufferedReader(reader);
this.separator = separator;
this.quotechar = quotechar;
this.skipLines = line;
}
public String[] readNext() throws IOException {
String nextLine = getNextLine();
return hasNext ? parseLine(nextLine) : null;
}
public String getNextLine() throws IOException {
if (!this.linesSkiped) {
for (int i = 0; i < skipLines; i++) {
br.readLine();
}
this.linesSkiped = true;
}
String nextLine = br.readLine();
if (nextLine == null) {
hasNext = false;
}
return hasNext ? nextLine : null;
}
public List<String[]> readAll() throws IOException {
List<String[]> allElements = new ArrayList<String[]>();
while (hasNext) {
String[] nextLineAsTokens = readNext();
if (nextLineAsTokens != null)
allElements.add(nextLineAsTokens);
}
return allElements;
}
private String[] parseLine(String nextLine) throws IOException {
if (nextLine == null) {
return null;
}
List<String> tokensOnThisLine = new ArrayList<String>();
StringBuffer sb = new StringBuffer();
boolean inQuotes = false;
do {
if (inQuotes) {
// continuing a quoted section, reappend newline
sb.append("\n");
nextLine = getNextLine();
linesCount++;
if (nextLine == null)
break;
}
for (int i = 0; i < nextLine.length(); i++) {
char c = nextLine.charAt(i);
if (c == quotechar) {
if( inQuotes
&& nextLine.length() > (i+1)
&& nextLine.charAt(i+1) == quotechar ){
sb.append(nextLine.charAt(i+1));
i++;
}else{
inQuotes = !inQuotes;
if(i>2
&& nextLine.charAt(i-1) != this.separator
&& nextLine.length()>(i+1) &&
nextLine.charAt(i+1) != this.separator
){
sb.append(c);
}
}
} else if (c == separator && !inQuotes) {
tokensOnThisLine.add(sb.toString());
sb = new StringBuffer();
} else {
sb.append(c);
}
}
} while (inQuotes);
tokensOnThisLine.add(sb.toString());
return (String[]) tokensOnThisLine.toArray(new String[0]);
}
public void close() throws IOException{
br.close();
}
}

You can construct an InputStreamReader from that InputStream
new InputStreamReader(myInputStream, encoding)
Where myInputStream is your InputStream and encoding is a String that defines the encoding used by your datasource.
You can call your CSVReader like this:
new CSVReader(new InputStreamReader(myInputStream, encoding));

Related

Could not find or load main class JavaCodeObfuscator

hey i write e java Obfuscator and build it using IntelliJ IDEA Artefact but when I enter arguments for obf file, the console outputs:
Error: Could not find or load main class JavaCodeObfuscator
Caused by: java.lang.ClassNotFoundException: JavaCodeObfuscator
Console Argument : java JavaCodeObfuscator hello.java
code:
import java.io.*;
import java.util.*;
public class JavaCodeObfuscator {
private static final int MIN_NAME_LENGTH = 4;
private static final int MAX_NAME_LENGTH = 8;
private static final int NAME_CHAR_SET_SIZE = 26;
private static final Random RANDOM = new Random();
public static void main(String[] args) {
if (args.length < 1) {
return;
}
String inputFile = args[0];
try {
String sourceCode = readSourceCode(inputFile);
String obfuscatedCode = obfuscate(sourceCode);
String outputFilePath = getOutputFilePath(inputFile);
writeObfuscatedCode(obfuscatedCode, outputFilePath);
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
}
private static String readSourceCode(String inputFile) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
StringBuilder sourceCodeBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sourceCodeBuilder.append(line).append("\n");
}
reader.close();
return sourceCodeBuilder.toString();
}
private static String obfuscate(String sourceCode) {
Map<String, String> nameMap = new HashMap<>();
StringBuilder obfuscatedCodeBuilder = new StringBuilder();
int nameCounter = 0;
for (int i = 0; i < sourceCode.length(); i++) {
char c = sourceCode.charAt(i);
if (Character.isJavaIdentifierStart(c)) {
StringBuilder nameBuilder = new StringBuilder();
nameBuilder.append(c);
while (i < sourceCode.length() - 1 && Character.isJavaIdentifierPart(c = sourceCode.charAt(++i))) {
nameBuilder.append(c);
}
String name = nameBuilder.toString();
String obfuscatedName = nameMap.get(name);
if (obfuscatedName == null) {
obfuscatedName = generateName(nameCounter++);
nameMap.put(name, obfuscatedName);
}
obfuscatedCodeBuilder.append(obfuscatedName);
i--;
} else {
obfuscatedCodeBuilder.append(c);
}
}
return obfuscatedCodeBuilder.toString();
}
private static String generateName(int index) {
StringBuilder nameBuilder = new StringBuilder();
int nameLength = MIN_NAME_LENGTH + RANDOM.nextInt(MAX_NAME_LENGTH - MIN_NAME_LENGTH + 1);
for (int i = 0; i < nameLength; i++) {
char c = (char) ('a' + RANDOM.nextInt(NAME_CHAR_SET_SIZE));
nameBuilder.append(c);
}
return nameBuilder.toString();
}
private static String getOutputFilePath(String inputFile) {
int dotIndex = inputFile.lastIndexOf('.');
String extension = dotIndex >= 0 ? inputFile.substring(dotIndex) : "";
String outputFileName = inputFile.substring(0, inputFile.length() - extension.length()) + "_obfuscated" + extension;
return outputFileName;
}
private static void writeObfuscatedCode(String obfuscatedCode, String outputFilePath) throws IOException {
PrintWriter writer = new PrintWriter(new FileWriter(outputFilePath));
writer.print(obfuscatedCode);
writer.close();
System.out.println("Protected");
}
}
Yes, I'm new to programming and maybe I did something wrong when building the original jar file

Array CompareFind Equals words only using array not array list

Have a two text file with words list. need save both file in two array.I know how to do it using list and set.. but here I want know how to do it using only arrays.Only array and no predefined functions such as Arrays.sort() or Collections.sort() can be used
no list no ArrayList or no class from Java Collection Frameworks can be used.
public class Main {
public static Set<String> setlist1= new HashSet<>();
public static String[] arrayList=new String[file1count];
public static String[] array2=new String[file2count];
public static int file1count=0;
public static int file2count=0;
public static void main(String[] args) {
try {
/*read the files*/
Scanner rf= new Scanner(new BufferedReader(new FileReader("D:\\IIT\\Project save\\New\\Inteli J\\OOPworkshop01\\file1.txt")));
Scanner rf2= new Scanner(new BufferedReader(new FileReader("D:\\IIT\\Project save\\New\\Inteli J\\OOPworkshop01\\file2.txt")));
String line;
String line2;
while(rf.hasNext()){
line=rf.nextLine();
file1count++;
}
while(rf2.hasNext()){
line2=rf2.nextLine();
file2count++;
}
rf.close();
rf2.close();
}catch(IOException e){
System.out.println(e);
}
}
}
The problem with using arrays is that you don't know in advance what length to allocate.
You basically have two options:
read each file twice
allocate an array of some initial length, and reallocate is as needed (that's what an ArrayList does.)
Second option: let's have a method readFile that reads all the lines from a file and returns an array:
public static String[] readFile(String fileName) throws IOException {
try (Reader reader = new FileReader(fileName);
BufferedReader in = new BufferedReader(reader)) {
String[] lines = new String[10]; // start with 10
int count = 0;
String line;
while ((line = in.readLine()) != null) {
if (count >= lines.length) {
lines = reallocate(lines, count, 2*lines.length);
}
lines[count++] = line;
}
if (count < lines.length) {
// reallocate to the final length;
lines = reallocate(lines, count, count);
}
return lines;
}
}
private static String[] reallocate(String[] lines, int count,
int newLength) {
String[] newArray = new String[newLength];
for (int i = 0; i < count; ++i) {
newArray[i] = lines[i];
}
lines = newArray;
return lines;
}
BufferedReader reader1 =
new BufferedReader(new FileReader("D:\\IIT\\Project save\\New\\Inteli J\\OOPworkshop01\\file1.txt"));
BufferedReader reader2 =
new BufferedReader(new FileReader("D:\\IIT\\Project save\\New\\Inteli J\\OOPworkshop01\\file2.txt"));
String line1 = reader1.readLine();
String[] array1 = new String[10000000];
String[] array2 = new String[10000000];
String line2 = reader2.readLine();
boolean areEqual = true;
int lineNum = 1;
while (line1 != null || line2 != null) {
if (line1 == null || line2 == null) {
areEqual = false;
break;
} else if (!line1.equalsIgnoreCase(line2)) {
areEqual = false;
break;
}
if (line1 != null) {
array1[lineNum] = line1;
}
if (line1 != null) {
array2[lineNum] = line2;
}
line1 = reader1.readLine();
line2 = reader2.readLine();
lineNum++;
}
if (areEqual) {
System.out.println("Same content.");
} else {
System.out.println("different content");
}
reader1.close();
reader2.close();
You can simply try above code.
Here I had used only WHILE loop, BufferedReader and FileReader.

Counting words, characters and lines

The method is to return an array counting the number of lines, words and characters in a document. After running it through a test file I am still receiving some errors.
public static int[] wc(Reader in) throws IOException {
int data = in.read();
int charcounter = 0;
int linecounter = 0;
int wordcounter = 0;
boolean previouswhitespace = false;
while (data != -1){
if (((char) data == '\n')){
linecounter++;
}
if (!(Character.isWhitespace((char) data))){
charcounter++;
if ((previouswhitespace == true) || (wordcounter == 0)){
previouswhitespace = false;
wordcounter++;
}
}
else if ((Character.isWhitespace((char) data))){
previouswhitespace = true;
}
data = in.read();
}
int[] array = {linecounter, wordcounter, charcounter};
return array;
}
//To choose the file
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File file = chooser.getSelectedFile();
String file_path = file.getAbsolutePath();
char[] c;
String [] words;
int charCounter = 0 ,wordsCounter = 0, lineCounter = 0;
//try and catch for the BufferedReader
try{
String line;
BufferedReader reader = new BufferedReader(new FileReader(file_path));
while( (line = reader.readLine()) !=null){
c = line.replace(" ","").toCharArray();
charCounter+=c.length;
words = line.split(" ");
wordsCounter+=words.length;
lineCounter++;
}
}catch(Exception e){
// Handle the Exception
}
int array[] = {charCounter , wordsCounter, lineCounter};
Hope this is helping you!

How to replace a String at a specific index in a text file in Java

My text file contains:
Hello This is a Test
Press Enter to Continue
I have an array of:
int StartIndex [] = {1,4,8}
int EndIndex [] = {3,7,11}
String[] VALUES = new String[] {"Sys","Jav","Tes"};
I want to replace index{1,3} with 'Sys', index{4,7} with 'Jav' and so on in the file.
My idea is to read the whole file as a String and then pass on the indexes to replace with the VALUES Strings.
How can I do this ?
CODE:
String[] VALUES = new String[] {"Sys"}; //Correct Solutions
int [] StartIndex ={4};
int [] EndIndex ={6};
while ((line = br.readLine()) != null) {
// Print the content on the console
System.out.println (line);
StringBuffer buf = new StringBuffer(line);
buf.replace(StartIndex[0], EndIndex[0], VALUES[0]);
done =buf.toString();
System.out.println(done);
Expected Ouput should be like this:
SyslJavhTes is a Test
Press Enter to Continue
I searched a bit and got this:
String myName = "domanokz";
char[] myNameChars = myName.toCharArray();
myNameChars[4] = 'x';
myName = String.valueOf(myNameChars);
If we convert the file to string and apply this function ,will this work?
Problem Solved! Code works perfectly because I tested it. Like before no comments have been added so you will understand & learn. (Please vote/accept answer if it works for others to identify the correct answer).
CODE:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
/**
*
* #author jtech
*/
public class ReplaceWithIndexes
{
public static void main(String[] args) throws IOException
{
BufferedReader br = null;
boolean endMatched = false;
int startIndex[] = {0,4,8};
int endIndex[] = {3,7,10};
int c = 0, c1 = 0, c2 = 0, largestVal_start = 0, largestVal_end = 0, lineCount = 0;
String line = null, newString = "";
String[] VALUES = new String[] {"Sys","Jav","Tes"};
br = new BufferedReader(new FileReader("C:\\Users\\jtech\\Documents\\NetBeansProjects\\HelpOthers\\src\\textFiles\\AnotherFile.txt"));
for (int i = 0; i < startIndex.length; i++)
{
if (startIndex[i] > largestVal_start)
{
largestVal_start = startIndex[i];
}
}
for (int i = 0; i < endIndex.length; i++)
{
if (endIndex[i] > largestVal_end)
{
largestVal_end = endIndex[i];
}
}
while ((line = br.readLine()) != null)
{
StringBuilder buf = new StringBuilder(line);
// Print the content on the console
System.out.println(line);
lineCount++;
while (c <= largestVal_start)
{
while (c1 <= largestVal_end)
{
if (startIndex[0] == c && endIndex[0] == c1)
{
buf.replace(startIndex[0], endIndex[0], VALUES[c2]);
newString = buf.toString();
endMatched = true;
}
else if (startIndex[1] == c && endIndex[1] == c1)
{
buf.replace(startIndex[1], endIndex[1], VALUES[c2]);
newString = buf.toString();
endMatched = true;
}
else if (startIndex[2] == c && endIndex[2] == c1)
{
buf.replace(startIndex[2], endIndex[2], VALUES[c2]);
newString = buf.toString();
endMatched = true;
}
c1++;
}
for (int i = 0; i < startIndex.length; i++)
{
if (c == startIndex[i])
{
c2++;
}
}
if (endMatched == true || ((c1 <= largestVal_end) == false) )
{
c1 = 0;
endMatched = false;
}
c++;
}
if (lineCount <= 1)
{
System.out.println("Updated line: " + newString);
}
}
}
}
In Java, the class is the proverbial hammer and every problem really is a nail. You need one for your case, too, instead of managing three separate arrays.
class Replacer {
private final int start, end;
private final String replacement;
Replacer(int start, int end, String replacement) {
this.start = start; this.end = end; this.replacement = replacement;
}
String replace(String in) {
StringBuilder b = new StringBuilder(in);
b.replace(start, end, replacement);
return b.toString();
}
}
Then create a list of replacers:
List<Replacer> replacers = Arrays.asList(
new Replacer(1, 3, "System"),
new Replacer(4, 7, "Java"),
new Replacer(8, 11, "Testing")
);
and apply them on each line:
while ((line = br.readLine()) != null) {
for (Replacer r : replacers) line = r.replace(line);
System.out.println(line);
}
The simplest solution would be the following code, but it's probably not efficient enough for huge files and/or large numbers of replaces.
while ((line = br.readLine()) != null) {
// Print the content on the console
System.out.println (line);
StringBuffer buf = new StringBuffer(line);
for (int i = 0; i < VALUES.length; i ++) {
buf = buf.replace(StartIndex[i], EndIndex[i], VALUES[i]);
}
done = buf.toString();
System.out.println(done);
}

How do i skip comments with buffer reader?

I have written the following program to read from a file and skip comments, it works for single line comments, but not for multi line ones. Does anyone know why? I don't need to worry about "//" in Strings. And only java comments ie "//" and "/* */"
code:
import java.io.*;
public class IfCounter2
{
public static boolean lineAComment(String line)
{
if (line.contains("//"))
return true;
return false;
}
public static boolean multiLineCommentStart(String line)
{
if (line.contains("/*"))
return true;
return false;
}
public static boolean multiLineCommentEnd(String line)
{
if (line.contains("*/"))
return true;
return false;
}
public static void main(String[] args) throws IOException
{
String fileName = args[0];
int numArgs = args.length;
int ifCount = 0;
// create a new BufferReader
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
String ls = System.getProperty("line.separator");
line = reader.readLine();
// read from the text file
boolean multiLineComment = false;
while (( line = reader.readLine()) != null)
{
if (!multiLineCommentStart(line))
{
multiLineComment = true;
}
if (multiLineComment) {
if (!multiLineCommentEnd(line))
{
multiLineComment = false;
}
}
if (!lineAComment(line) && !multiLineComment)
{
stringBuilder.append(line);
stringBuilder.append(ls);
}
}
// create a new string with stringBuilder data
String tempString = stringBuilder.toString();
System.out.println(stringBuilder.toString());
}
}
You only set multiLineComment to true when !multiLineCommentStart(line) is true - that is, whenever the line does not contain /*.
Basically, your code should look sth like this (untested)
boolean multiLineComment = false;
while (( line = reader.readLine()) != null)
{
if (multiLineCommentStart(line))
{
multiLineComment = true;
}
if (multiLineComment) {
if (multiLineCommentEnd(line))
{
multiLineComment = false;
}
}
if (!lineAComment(line) && (multiLineComment == false))
{
stringBuilder.append(line);
stringBuilder.append(ls);
}
}
in that last if statement, you need to have an expression with your variable and a fixed
Andy's answer is right on the money but needs a validation in last if to make sure you are not counting */ as a valid line:
boolean multiLineComment = false;
while (( line = reader.readLine()) != null)
{
if (multiLineCommentStart(line))
{
multiLineComment = true;
}
if (multiLineComment) {
if (multiLineCommentEnd(line))
{
multiLineComment = false;
}
}
if (!lineAComment(line) && (multiLineComment == false) &&
!multiLineCommentEnd(line) )
{
stringBuilder.append(line);
stringBuilder.append(ls);
}
}

Categories