Getting arrayoutofbond error while running java code - java

I am getting arrayoutofbond error while running below given code,
sometime it is running as expected and sometime it is giving error.
Could anyone help me where I am wrong.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
public class getFileContent{
public void listFiles() throws IOException, InterruptedException{
File directory = new File("C:\\ScriptLogFile\\");
File[] myarray;
myarray=directory.listFiles();
int i=0;
ArrayList<String> arrayList = new ArrayList<String>();
SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy_hhmmss");
Date curDate = new Date();
String strDate = sdf.format(curDate);
String fileName = strDate;
File file = new File("C:\\ExcelReport_"+fileName+".csv");
FileWriter fileWritter = new FileWriter(file, true);
BufferedWriter bwr = new BufferedWriter(fileWritter);
String filename = null;
try {
for (int j = 0; j < myarray.length; j++)
{
File path=myarray[j];
FileInputStream fis = new FileInputStream (path);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
if(path.isFile()){
if(path.getName().endsWith(".csv")){
filename = path.getName();
String line;
bwr.write(filename+",");
while ((line = br.readLine()) != null) {
if(line.contains("-")){
String[] part = line.split("-");
arrayList.add(part[1]);
bwr.write(arrayList.get(i)+",");
i++;
}
else{
}
}
bwr.write("\r\n");
}
}
}
}catch (FileNotFoundException e) {
e.printStackTrace();
}
bwr.close();
}
public static void main(String[] args) throws IOException, InterruptedException {
getFileContent gfc = new getFileContent();
gfc.listFiles();
}
}

We need a stack trace to see where the exception is raised. However you seem to be making assumptions about the length of part[]. Remember arrays are 0-indexed, the first entry would be at index 0 i.e. part[0]. Even then, in general there really needn't be many entries at all: "xyz".split("-") is an array of length 1 whose only element, "xyz", is at index 0.

Related

Why program did not show answer in out.txt?

The code should do a reverse and output the result to out.txt, but this does not happen, can you explain my mistake in the code. Thanks in advance
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
FileReader input = new FileReader("in.txt");
FileWriter output = new FileWriter("out.txt");
BufferedReader sb = new BufferedReader(input);
String data;
while ((data = sb.readLine()) != null) {
String[] words = data.split(" ");
for (String a : words) {
StringBuilder builder = new StringBuilder(a);
builder.reverse();
while ((sb.read()) != -1) {
output.write(String.valueOf(builder.reverse()));
}
}
}
}
}
You are trying to reverse the string twice because of that the string is getting back to the original string. Also, there is an unnecessary (as per my understanding) while loop inside the for loop (I have removed that in my answer).
Try the below code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
FileReader input = new FileReader("in.txt");
FileWriter output = new FileWriter("out.txt");
BufferedReader sb = new BufferedReader(input);
String data;
while ((data = sb.readLine()) != null) {
String[] words = data.split(" ");
// above statement can be replaced with
// String[] words = data.split(" {34}");
for (String a : words) {
StringBuilder builder = new StringBuilder(a);
// why while loop is required?
//while ((sb.read()) != -1) {
output.write(builder.reverse().toString());
output.flush(); // flush data to the file
//}
}
}
output.close();
}
}
Read about File writer here on how to flush data and also close the writer after writing is completed.

Not able to upload JSON in MongoDB using Java

I am trying to upload JSON file in MongoDB using Documents, but getting the following error. I'm new to Mongo. Can I get any help?
Exception in thread "main" org.bson.BsonInvalidOperationException: readStartDocument can only be called when CurrentBSONType is DOCUMENT, not when CurrentBSONType is ARRAY.
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.MongoClient;
import java.io.*;
import com.mongodb.client.model.BulkWriteOptions;
import com.mongodb.client.model.InsertOneModel;
import org.bson.Document;
import java.io.FileReader;
import java.io.BufferedReader;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
//System.out.println(new File("").getAbsolutePath());
// Creating a Mongo client
MongoClient client = new MongoClient("localhost", 27017);
MongoDatabase database = client.getDatabase("mongotest");
MongoCollection<Document> collection = database.getCollection("jsondata");
int count = 0;
int batch =100;
List<InsertOneModel<Document>> docs = new ArrayList<>();
//System.out.println(docs.getClass().getName());
try (BufferedReader br = new BufferedReader(new FileReader("mongotest.json"))) {
String line;
while ((line = br.readLine()) != null) {
// System.out.println(Document.parse(line));
docs.add(new InsertOneModel<>(Document.parse(line)));
count++;
if (count == batch) {
collection.bulkWrite(docs, new BulkWriteOptions().ordered(false));
docs.clear();
count = 0;
}
}
}
catch(FileNotFoundException e) {
System.out.println("The file doesn't exist");
}
catch(IOException e){
System.out.println("The file could not be read");
}
}
}
Can you share the mongotest.json contents?
Each line must be an object (surrounded in {}), not an array (surrounded in []).
Edit:
To fix your issue, instead of reading using BufferedReader do this:
...
var json = Files.readString("mongotest.json", StandardCharsets.UTF_8);
var jsonarray = new JSONArray(json);
for (int i = 0; i < jsonarray.length(); i++) {
var line = jsonarray.getJSONObject(i);
docs.add(new InsertOneModel<>(Document.parse(line.toString())));
count++;
}
...

Unable to copy txt file over to arraylist and into file

I am attempting to add this large txt file into an array list then sort the data. Then put 15000 lines in various temp files. I am unable to put the data into each file. Here is my code:
package bigfilesorter2;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class bigfilesorter2 {
public static final int NUM_LINES = 15000;
public static void main(String args[]) throws IOException {
FileReader fileReader = new FileReader("Aesop_Shakespeare_Shelley_Twain.txt");
BufferedReader br = new BufferedReader(fileReader);
ArrayList<String> arraylist = readingfile(br);
//System.out.println(arraylist);
makingfiles(br, arraylist);
}
public static void makingfiles(BufferedReader br, ArrayList<String> arraylist) throws IOException {
int start = 0;
int end = 15000;
for(int i = 0; i < 20; i++) {
File file = new File("/Users/domlanza/desktop/testing/Filee"+i+".txt");
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
for(;start <= end; start++){
bw.write(arraylist.get(start));
bw.newLine();
}
bw.flush();
bw.close();
fw.close();
start = end + 1;
end += 15000;
}
}
public static ArrayList<String> readingfile(BufferedReader br) throws FileNotFoundException, IOException {
//Read in file
Scanner s = new Scanner(new File("Aesop_Shakespeare_Shelley_Twain.txt"));
int count = 0;
ArrayList<String> arraylist = new ArrayList<String>();
while (s.hasNext()) {
count++;
arraylist.add(s.nextLine());
}
//} catch (IOException e) {e.printStackTrace();}
Collections.sort(arraylist);
//System.out.println(arraylist);
return arraylist;
}
}
Any help would be appreciated. the commas were just the file being sorted..................
"it looks like your post is mostly code"
You need to create a list of sublists where each sublist holds 15000 lines. Given below is the complete code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
public class BigFileSorter {
public static final int NUM_LINES = 15000;
public static final int NUM_FILES = 20;
public static void main(String args[]) throws IOException {
FileReader fileReader = new FileReader("file.txt");
BufferedReader br = new BufferedReader(fileReader);
ArrayList<ArrayList<String>> list = readingfile(br);
makingfiles(br, list);
}
public static void makingfiles(BufferedReader br, ArrayList<ArrayList<String>> list) throws IOException {
if (list != null) {
for (int i = 0; i < NUM_FILES; i++) {
File file = new File("Filee" + i + ".txt");
FileWriter fw = new FileWriter(file);
ArrayList<String> subList = list.get(i);
for (String str : subList) {
fw.write(str + System.lineSeparator());
}
fw.close();
}
}
}
public static ArrayList<ArrayList<String>> readingfile(BufferedReader br)
throws FileNotFoundException, IOException {
ArrayList<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
ArrayList<String> subList;
String line;
try {
for (int i = 0; i < NUM_FILES; i++) {
subList = new ArrayList<String>();
for (int j = 0; j < NUM_LINES; j++) {
line = br.readLine();
if (line == null) {
break;
}
subList.add(line);
}
Collections.sort(subList);
list.add(subList);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
br.close();
}
return list;
}
}
Feel free to comment in case of any doubt.
Maybe something like this as an inner for loop in your makefiles method.
// outside of the for loops
int start = 0;
int end = 15000;
// inner for loop
for(;start <= end; start++){
bw.write(arraylist.get(start));
bw.newline();
}
// end of outer for loop
start = end + 1;
end += 15000;
So complete method:
public static void makingfiles(BufferedReader br, ArrayList<String> arraylist) throws IOException {
int start = 0;
int end = 15000;
for(int i = 0; i < 20; i++) {
File file = new File("/Users/domlanza/desktop/testing/Filee"+i+".txt");
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
for(;start <= end; start++){
bw.write(arraylist.get(start));
bw.newline();
}
bw.flush();
bw.close();
fw.close()
start = end + 1;
end += 15000;
}
}
Should work for what you asked in the comment, but you still have to change your read method so that it reads all the lines in one arraylist

Eclipse CDT ASTRewrite not working

I want to add some code to the C source code, so I try to use ASTRewrite.
My Github project: cdt-rewrite
My code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import org.eclipse.cdt.core.dom.ast.ASTVisitor;
import org.eclipse.cdt.core.dom.ast.IASTIfStatement;
import org.eclipse.cdt.core.dom.ast.IASTStatement;
import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit;
import org.eclipse.cdt.core.dom.ast.gnu.c.GCCLanguage;
import org.eclipse.cdt.core.dom.rewrite.ASTRewrite;
import org.eclipse.cdt.core.model.ILanguage;
import org.eclipse.cdt.core.parser.DefaultLogService;
import org.eclipse.cdt.core.parser.FileContent;
import org.eclipse.cdt.core.parser.IncludeFileContentProvider;
import org.eclipse.cdt.core.parser.ScannerInfo;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.ltk.core.refactoring.Change;
public class Main {
public static void main(String[] args) throws Exception {
IASTTranslationUnit u = getTranslationUnit(new File("D:/test.c"));
System.out.println(u.getRawSignature());
ASTRewrite rw = ASTRewrite.create(u);
u.accept(new ASTVisitor(true) {
#Override
public int visit(IASTStatement stm) {
if (stm instanceof IASTIfStatement){
rw.insertBefore(stm.getParent(), stm,
rw.createLiteralNode("callTo(1,2,3);"), null);
}
return PROCESS_CONTINUE;
}
});
Change c = rw.rewriteAST();
c.perform(new NullProgressMonitor());
//String changedSource = someHowGetCode(c);
}
static IASTTranslationUnit getTranslationUnit(File source) throws Exception{
FileContent reader = FileContent.create(
source.getAbsolutePath(),
getContentFile(source).toCharArray());
return GCCLanguage.getDefault().getASTTranslationUnit(
reader,
new ScannerInfo(),
IncludeFileContentProvider.getSavedFilesProvider(),
null,
ILanguage.OPTION_IS_SOURCE_UNIT,
new DefaultLogService());
}
static String getContentFile(File file) throws IOException {
StringBuilder content = new StringBuilder();
String line;
try (BufferedReader br = new BufferedReader(
new InputStreamReader(new FileInputStream(file)))) {
while ((line = br.readLine()) != null)
content.append(line).append('\n');
}
return content.toString();
}
}
But when I run this code, an exception is occur:
int test(int x){
if (x < 0)
return 0;
int i, s = 0;
for (i = 1; i < x; i++)
s = s + i;
return s;
}
Exception in thread "main" java.lang.NullPointerException
at org.eclipse.cdt.internal.formatter.ChangeFormatter.formatChangedCode(ChangeFormatter.java:92)
at org.eclipse.cdt.internal.core.dom.rewrite.changegenerator.ChangeGenerator.generateChange(ChangeGenerator.java:117)
at org.eclipse.cdt.internal.core.dom.rewrite.changegenerator.ChangeGenerator.generateChange(ChangeGenerator.java:104)
at org.eclipse.cdt.internal.core.dom.rewrite.ASTRewriteAnalyzer.rewriteAST(ASTRewriteAnalyzer.java:26)
at org.eclipse.cdt.core.dom.rewrite.ASTRewrite.rewriteAST(ASTRewrite.java:212)
at Main.main(Main.java:44)
Does anyone know how to solve this exception?
Thanks you
AFAIK This code is dependent on running in OSGi, but you appear to have made a Java project with a main. You need to a plug-in project with a MANIFEST.MF that references what you require.
You can create an Eclipse Application if you want to control the entry point to the program. If you want to graduate this rewriting code to be part of Eclipse/CDT, then different entry points such as an Eclipse Command tied to a menu/toolbar/key combination may be what you want.

I like to add quotes inside a string gathered from the readLine()

The output is
INSERT INTO 'products'('productid', 'color', 'size', 'price') VALUES ('purse8901, red, small handbag, 70.00');
I would like to have the single straight quotes added so that I can import the converted sql file easily into the database again like this:
INSERT INTO 'products'('productid', 'color', 'size', 'price') VALUES
('purse8901', 'red', 'small handbag', '70.00');
The problem is that I can't figure out how to split the sCurrentLine string and add \' above.
package ConvertCSVtoSQL;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Convert {
public static void main(String[] args) throws IOException {
String begin = "INSERT INTO `produts`(`productid`, `color`. `size`,
`price`) VALUES ('";
File fileToSave = new File("C:\\Users\\Blue\\Desktop\\sql\
\products.sql");
if (!fileToSave.exists()) {
fileToSave.createNewFile();
}
FileWriter fw = new FileWriter(fileToSave.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write('\n');
String end = "');";
String sCurrentLine;
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("C:\\Users\\Blue\\Desktop\
\products.csv"));
} catch (FileNotFoundException ex) {
Logger.getLogger(Convert.class.getName()).log(Level.SEVERE, null,
ex);
}
br.readLine();
for (int count = 1; count <= 236; count++) {
sCurrentLine = br.readLine();
bw.write(begin + sCurrentLine + end);
bw.write('\n');
}
bw.close();
}
}
May be you are looking for something like this:-
String name = "\'productid\'";

Categories

Resources