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
Related
Currently I am facing a problem during sorting. I can sort my data (in a csv file) using insertion sort by the ID, but i get results like this:
14000027,Sofia Bonfiglio
14000053,Ashlee Capellan
14000310,Dona Mcinnes
14000436,Maricela Landreneau
14000688,Elinor Raco
but the original ID for those names are:
14495655 Sofia Bonfiglio
14224671 Ashlee Capellan
14707100 Dona Mcinnes
14644633 Maricela Landreneau
14147356 Elinor Raco
I am currently stuck. Any tips will help me by a lot, thank you!
Heres my code:
public class NameSorting{
private static void readFiles(String inFileName) throws IOException{
FileInputStream fileStream = null;
InputStreamReader rdr;
BufferedReader bufRdr;
int lineNum;
String line;
try{
fileStream = new FileInputStream(inFileName);
rdr = new InputStreamReader(fileStream);
bufRdr = new BufferedReader(rdr);
String[] nameArray = new String[7000];
Long[] idArray = new Long[7000];
String[] rowArray = new String[2];
int i = 0;
lineNum = 0;
line = bufRdr.readLine();
while (line != null){
lineNum++;
rowArray = processLine(line);
//stores the returned split value into two arrays, idArray and nameArray
idArray [i] = Long.parseLong(rowArray[0]);
nameArray [i] = rowArray[1];
i++;
line = bufRdr.readLine();
}
sorts(idArray, nameArray); //sorts the file by id
fileStream.close();
}
catch(IOException e){
if (fileStream != null){
try {
fileStream.close();
}
catch (IIOException ex2){
}
}
System.out.println("Error in file processing" + e.getMessage());
}
}
private static String[] processLine(String csvRow){ //takes in a row from the CSV file and splits it with comma, returns rowArray.
String[] rowArray = new String[2];
rowArray = csvRow.split(",");
return rowArray;
}
private static void write(Long[] idArray, String[] nameArray) {
FileOutputStream fileStrm = null;
PrintWriter pw;
String inFileName = "Sorted.txt";
try {
fileStrm = new FileOutputStream(inFileName);
pw = new PrintWriter(fileStrm);
for (int k = 0; k < idArray.length; k++){
pw.println(idArray[k] + "," + nameArray[k]);
}
pw.close();
} catch (IOException e) {
System.out.println("Error in writing to file: " + e.getMessage());
}
}
private static void sorts(Long[] idArray, String[] nameArray){
for (int pass = 1; pass < idArray.length ; pass++){
int hold = pass;
Long temp = idArray[hold];
while (hold > 0 && (idArray[hold - 1] > temp)){
idArray[hold] = idArray[hold - 1];
hold = hold - 1;
}
idArray[hold] = temp;
}
write(idArray, nameArray);
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter file name");
String inp = sc.next();
readFiles(inp);
System.out.println("Done");
}
}
It is possible to solve the problem using a Treemap<Integer, String> using the id as key and after with streams convert the map to an array like below:
public class NameSorting {
public static void main(String[] args) {
String[] lines = {"14495655 Sofia Bonfiglio",
"14224671 Ashlee Capellan",
"14707100 Dona Mcinnes",
"14644633 Maricela Landreneau",
"14147356 Elinor Raco" };
Map<Long, String> map = new TreeMap<>();
for (String line : lines) {
String[] arr = line.split(" ", 2);
map.put(Long.parseLong(arr[0]), arr[1]);
}
String[] mapAsStringArray = map.keySet().stream()
.map(key -> key + "," + map.get(key))
.toArray(String[]::new);
for (String line : mapAsStringArray) {
System.out.println(line);
}
}
}
The output will be ordered:
14147356,Elinor Raco
14224671,Ashlee Capellan
14495655,Sofia Bonfiglio
14644633,Maricela Landreneau
14707100,Dona Mcinnes
Need your help guys.The problem I have is in my code.While I am using RandomAccessFile I don't have any problem in writing or reading the file.But if I am trying to use ObjectInputStream with BufferedInputStream the file can't be read fully(only the first Object).
Here is my code of 2 different ways of reading and writing through stream or RandomAccessFile
public static final String FNAME1 = "1.dat";
public static final String FNAME2 = "2.dat";
final static int ID_SIZE = 10;
final static int NAME_SIZE = 20;
final static int GRADE_SIZE = 5;
final static int RECORD_SIZE = (ID_SIZE + NAME_SIZE + GRADE_SIZE) * 2; // *2 because of the UNI-CODE.
private static Scanner s = new Scanner(System.in);
public static void main(String[] args){
int studNum;
System.out.println("Please enter how many students: ");
studNum=s.nextInt();
Student<?>[] a = new Student[studNum];
try{
createArrary(a,studNum);
save(a,FNAME1);
System.out.println("2.dat saved successfully!! \n");
fileCopy(FNAME1,FNAME2);
System.out.println("The Students in file: ");
read(FNAME2);
bubbleSort(FNAME1);
fileCopy(FNAME1,FNAME2);
System.out.println("2.dat after sorting:");
read(FNAME2);
}catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**Creates array of Students.*/
public static Student<?>[] createArrary(Student<?>[] a,int studNum) {
String input="";
for(int i = 0; i < studNum; i++) {
System.out.println("Student # "+(i+1)+":");
System.out.print("\nPlease enter the student's id: ");
int id = s.nextInt();
System.out.print("\nPlease enter Student's name : ");
s.nextLine();
String name = s.nextLine();
System.out.print("\nPlease enter Student's grade ");
input=s.nextLine();
if(isInteger(input)){
a[i]=new Student<>(id, name,Integer.parseInt(input));
}else{
a[i]=new Student<>(id,name,input);
}
}
return a;
}
/**Check if string has integer num.*/
public static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
} catch(NullPointerException e) {
return false;
}
return true;
}
/**Save Student array to the file.*/
public static void save(Student<?>[] a,String fileName) throws FileNotFoundException, IOException {
try (RandomAccessFile f = new RandomAccessFile(fileName, "rw")) {
f.setLength(0);
for (Student<?> p : a) {
writeFixedLengthString(String.valueOf(p.getId()),ID_SIZE,f);
writeFixedLengthString(p.getFullName(),NAME_SIZE,f);
writeFixedLengthString(String.valueOf(p.getGrade()),GRADE_SIZE,f);
}
}
}
public static void save(Student<?>[] a,String fileName) throws FileNotFoundException, IOException {
try(ObjectOutputStream o = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(fileName)))){
for(Student<?> p : a){
writeFixedLengthString(String.valueOf(p.getId()),ID_SIZE,o);
writeFixedLengthString(p.getFullName(),NAME_SIZE,o);
writeFixedLengthString(String.valueOf(p.getGrade()),GRADE_SIZE,o);
}
}
}
/**Read Students from file.*/
public static void read(String fileName) throws FileNotFoundException, IOException,NumberFormatException {
try (RandomAccessFile f = new RandomAccessFile(fileName, "r")) {
while (f.getFilePointer() < f.length()) {
int id=Integer.parseInt(readFixedLengthString(ID_SIZE,f));
String name=readFixedLengthString(NAME_SIZE,f);
String grade=readFixedLengthString(GRADE_SIZE,f);
System.out.println(new Student<>(id, name,grade));
}
}
}
public static void read(String fileName) throws FileNotFoundException, IOException,NumberFormatException {
BufferedInputStream f;
try(ObjectInputStream i = new ObjectInputStream(f = new BufferedInputStream(new FileInputStream(fileName)))){
while (f.available() > 0) {
int id=Integer.parseInt((readFixedLengthString(ID_SIZE,i)));
String name=readFixedLengthString(NAME_SIZE,i);
String grade=readFixedLengthString(GRADE_SIZE,i);
System.out.println(new Student<>(id, name,grade));
}
}
}
/** Write fixed number of characters to a DataOutput stream */
public static void writeFixedLengthString(String s, int size,
DataOutput out) throws IOException
{ char[] chars = new char[size];
s.getChars(0, Math.min(s.length(), size), chars, 0);
for (int i = s.length(); i < size; i++)
chars[i] = ' ';
out.writeChars(new String(chars));
}
/** Read fixed number of characters from a DataInput stream */
public static String readFixedLengthString(int size, DataInput in)
throws IOException
{ char[] chars = new char[size];
for (int i = 0; i < size; i++)
chars[i] = in.readChar();
return new String(chars).replaceAll(" ", "");
}
/** Copying source file to destination file */
public static void fileCopy(String fileSource,String fileDest) throws FileNotFoundException,IOException{
try(BufferedInputStream input=new BufferedInputStream(new FileInputStream(fileSource));BufferedOutputStream output =new BufferedOutputStream(new FileOutputStream(fileDest));){
int r;
while ((r = input.read()) != -1)
{ output.write(r);
}
}
}
/** Read Students from file and returns Object */
public static <T> Student<?> readSort(RandomAccessFile f) throws FileNotFoundException, IOException,NumberFormatException {
int id=Integer.parseInt(readFixedLengthString(ID_SIZE,f));
String name=readFixedLengthString(NAME_SIZE,f);
String grade=readFixedLengthString(GRADE_SIZE,f);
return new Student<>(id, name,grade);
}
/** Receive Student Objects and Save them to file */
public static <T> void saveSort(Student<T> stud,RandomAccessFile f) throws FileNotFoundException, IOException {
writeFixedLengthString(String.valueOf(stud.getId()),ID_SIZE,f);
writeFixedLengthString(stud.getFullName(),NAME_SIZE,f);
writeFixedLengthString(String.valueOf(stud.getGrade()),GRADE_SIZE,f);
}
/** Bubble Sort of Student's grades */
#SuppressWarnings("unchecked")
public static <T> void bubbleSort(String file) throws FileNotFoundException, IOException {
try (RandomAccessFile raf = new RandomAccessFile(file, "rw")) {
boolean needNextPass = true;
for (int k = 1; k < raf.length() / RECORD_SIZE && needNextPass; k++) {
needNextPass = false;
for (int i = 0; i < (raf.length() / RECORD_SIZE) - k; i++) {
raf.seek(RECORD_SIZE * i);
long tmpPrev = raf.getFilePointer();
Student<T> prevStud = (Student<T>) readSort(raf);
long tmpNext = raf.getFilePointer();
Student<T> nextStud = (Student<T>) readSort(raf);
if(isInteger((String) prevStud.getGrade())&&isInteger((String) nextStud.getGrade())){
if(Integer.parseInt((String) prevStud.getGrade())>Integer.parseInt((String) nextStud.getGrade())){
Student<T> temp=prevStud;
prevStud = nextStud;
nextStud = temp;
raf.seek(tmpPrev);
saveSort(prevStud, raf);
raf.seek(tmpNext);
saveSort(nextStud, raf);
needNextPass = true;
}
}else if(String.valueOf(prevStud.getGrade())
.compareTo(String.valueOf(nextStud.getGrade())) > 0 &&!isInteger((String) prevStud.getGrade())&&!isInteger((String) nextStud.getGrade())){
Student<T> temp=prevStud;
prevStud = nextStud;
nextStud = temp;
raf.seek(tmpPrev);
saveSort(prevStud, raf);
raf.seek(tmpNext);
saveSort(nextStud, raf);
needNextPass = true;
}else if(isInteger((String) prevStud.getGrade())&&!isInteger((String) nextStud.getGrade())||!isInteger((String) prevStud.getGrade())&&isInteger((String) nextStud.getGrade())&&String.valueOf(prevStud.getGrade())
.compareTo(String.valueOf(nextStud.getGrade())) < 0){
Student<T> temp=prevStud;
prevStud = nextStud;
nextStud = temp;
raf.seek(tmpPrev);
saveSort(prevStud, raf);
raf.seek(tmpNext);
saveSort(nextStud, raf);
needNextPass = true;
}
}
}
}
}
}
ok I understand I can just write like this.
public static void read(String fileName) throws FileNotFoundException, IOException,NumberFormatException {
try(ObjectInputStream i = new ObjectInputStream(new BufferedInputStream(new FileInputStream(fileName)))){
while (i.available()>0) {
int id=Integer.parseInt((readFixedLengthString(ID_SIZE,i)));
String name=readFixedLengthString(NAME_SIZE,i);
String grade=readFixedLengthString(GRADE_SIZE,i);
System.out.println(new Student<>(id, name,grade));
}
}
}
But how I can translate inputstream to RandomAccessFile ?
I want to be able to read in 20 random names from the file and put them into a new file. How do i go about this?
public class Assignment2 {
public static void main(String[] args) throws IOException
{
// Read in the file into a list of strings
BufferedReader reader = new BufferedReader(new FileReader("textfile.txt"));
//BufferedWriter bw = new BufferedWriter(new FileWriter("out.txt"));
List<String> lines = new ArrayList<String>();
String line = reader.readLine();
while( line != null ) {
lines.add(line);
line = reader.readLine();
}
// Choose a random one from the list
Random r = new Random();
for (int i = 0; i < 20; i++)
{
int rowNum = r.nextInt(lines.size ());
System.out.println(lines.get(rowNum));
}
}
}
try (BufferedWriter writer = new BufferedWriter(new FileWriter("randomNames.txt"))) {
Random random = new Random();
for (int i = 0; i < 20; i++) {
int rowNum = random.nextInt(lines.size());
writer.write(lines.get(rowNum));
writer.newLine();
}
}
If you need to check if some number was already used, add it to a set:
try (BufferedWriter writer = new BufferedWriter(new FileWriter("randomNames.txt"))) {
Set<Integer> usedNumbers = new HashSet<Integer>(20);
Random random = new Random();
int addedCount = 0;
while (addedCount < 20) {
int rowNum = random.nextInt(lines.size());
if (usedNumbers.add(rowNum)) {
writer.write(lines.get(rowNum));
writer.newLine();
addedCount++;
}
}
}
To check if there is another name with same first character:
private static void containsNameWithSameFirstCharacter(Collection<String> names, String name) {
for (String anotherName : names) {
if (anotherName.charAt(0) == name.charAt(0)) {
return true;
}
}
return false;
}
Then you do:
Random random = new Random();
Set<String> usedNames = new HashSet<String>(20);
while (usedNames.size() < 20) {
int rowNum = random.nextInt(lines.size());
String name = lines.get(rowNum);
if (!containsNameWithSameFirstCharacter(usedNames, name)) {
usedNames.add(name);
writer.write(name);
writer.newLine();
}
}
I'm getting an error can someone help me with the following code:
it is supposed to perform preprocesing
// program to perform preprocess
public static void main(String[] args) {
//public class PreProcess {
// Read a file into a string. Takes file path, returns string
/**
*
* #param path
* #return
*/
public String readFileIntoString(String path) {
char[] line = new char[1024];
StringBuilder dataString;
dataString = new StringBuilder(5000);
try {
try (BufferedReader input = new BufferedReader(new FileReader(path))) {
while (true) {
int readLength = input.read(line);
if (readLength == -1)
break;
dataString.append(line, 0, readLength);
}
}
return dataString.toString();
}
catch (IOException e) {
return " ";
}
}
// Removes stop words from a string. Takes stop word file path and returns
// string
public static String removeStopWords(String fileData, String stopWordFilePath) {
String newfile = fileData;
String line;
try {
BufferedReader input = new BufferedReader(new FileReader(stopWordFilePath));
while ((line = input.readLine()) != null) {
if (line.compareTo("") == 0)
continue;
line = " " + line + " ";
newfile = newfile.replaceAll(line, " ");
}
input.close();
}
catch (IOException e) {
e.printStackTrace();
}
return newfile;
}
public static String removeHTMLTags(String fileData) {
return strip(fileData);
}
// Filtering to a given windowsize for query terms. Takes query and size,
// returns string
public static String filterToWindow(String query, String fileData, int windowSize) {
StringBuffer dataString = new StringBuffer(5000);
String[] fileWords = fileData.split(" ");
String[] queryWords = query.split(" ");
int[] markWords = new int[fileWords.length];
for (int i = 0; i < fileWords.length; i++) {
markWords[i] = 0;
}
for (int i = 0; i < fileWords.length; i++) {
for (int j = 0; j < queryWords.length; j++) {
if (fileWords[i].compareTo(queryWords[j]) == 0) {
for (int k = 0; k < windowSize; k++) {
if (i + k < fileWords.length)
markWords[i + k] = 1;
if (i - k > 0)
markWords[i - k] = 1;
}
}
}
}
for (int i = 0; i < fileWords.length; i++) {
if (markWords[i] == 1) {
dataString.append(fileWords[i]);
dataString.append(" ");
}
}
return dataString.toString();
}
public static void extractMetaData(String fileData, String linkFilePath, int docId) {
int urlEnd = 0, urlStart = 0;
StringBuilder b3 = new StringBuilder();
StringBuilder b2 = new StringBuilder();
fileData = fileData.toLowerCase();
try {
String title = fileData.substring(fileData.indexOf("<title"), fileData.indexOf("</title>")).replaceAll("\\<.*?>", "");
writeStringIntoFile(title, linkFilePath + docId + ".title");
}
catch (Exception e) {
}
while (true) {
urlStart = fileData.indexOf("a href=\"", urlEnd) + 8;
if (urlStart == 7)
break;
urlEnd = fileData.indexOf('\"', urlStart + 1);
String link = fileData.substring(urlStart, urlEnd);
int linkstart = 0;
int linkend = link.length() - 1;
if (link.startsWith("http"))
link = link.substring(7);
while (link.startsWith("/"))
link = link.substring(1);
if (!link.startsWith("#")) {
if (link.indexOf('/') != -1)
link = link.substring(0, link.indexOf('/'));
if (!link.contains("wiki") && !link.contains("myspace.com") && !link.contains("javascript")) {
b3.append(link);
b3.append("\n");
}
}
}
writeStringIntoFile(b3.toString(), linkFilePath + docId + ".links");
urlEnd = 0;
while (true) {
urlStart = fileData.indexOf("src=\"", urlEnd) + 5;
if (urlStart == 4)
break;
urlEnd = fileData.indexOf('\"', urlStart + 1);
String link = fileData.substring(urlStart, urlEnd);
if (!link.startsWith("#")) {
if (!link.startsWith("/")) {
link = link.substring(0, link.lastIndexOf('/') + 1);
}
b2.append(link);
b2.append("\n");
}
}
writeStringIntoFile(b2.toString(), linkFilePath + docId + ".images");
}
// Saves a string to a file. Takes string and file path
public static void writeStringIntoFile(String fileData, String path) {
try {
try (BufferedWriter output = new BufferedWriter(new FileWriter(path))) {
output.write(fileData);
}
}
catch (IOException e) {
}
}
private static String strip(String inputString) {
inputString = inputString.replaceAll("\\<style.*?</style>", " ");
inputString = inputString.replaceAll("\\<script.*?</script>", " ");
inputString = inputString.replaceAll("\\<.*?>", " ").replaceAll("[^A-Za-z]+", " ").replaceAll("\\s+", " ");
inputString = inputString.trim();
// inputString = PorterStemmer.applyStemmer(inputString);
return inputString;
}
}
}
You've declared methods inside your main()
public static void main(String[] args) {
public String readFileIntoString(String path) {
char[] line = new char[1024];
StringBuilder dataString;
...
You cannot do this. Methods cannot be nested inside methods. Take them out
public static void main(String[] args) {
...
}
public String readFileIntoString(String path) {
char[] line = new char[1024];
StringBuilder dataString;
...
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));