I keep getting an ArrayIndexOutOfBoundsException, but I am not sure what part of code exactly causes this error. Any help will be appreciated a lot. The code is
while ((line = reader.readLine()) != null) {
String[] wordOnLine = line.split(",");
geo.put(wordOnLine[0] , new GeoLocation(wordOnLine[0], Double.parseDouble(wordOnLine[1]), Double.parseDouble(wordOnLine[2]),TimeZone.getTimeZone(wordOnLine[3])));
}
The error is
Unable to start activity
ComponentInfo{swindroid.suntime/swindroid.suntime.ui.Main}:
java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
public List getListOfLocations() {
// String fileName = "au_locations.txt";
// BufferedReader reader = null;
// StringBuilder builder = new StringBuilder();
InputStream input = getResources().openRawResource(R.raw.au_locations);
BufferedReader reader = new BufferedReader( new InputStreamReader((input)));
String line;
StringBuilder builder = new StringBuilder();
File file = new File(getFilesDir(), "au_locations.txt");
try {
// reader = new BufferedReader(new InputStreamReader(getAssets().open(fileName)));
// String line;
while ((line = reader.readLine()) != null) {
// builder.append(line).append("\n");
String[] wordOnLine = line.split(",");
geo.put(wordOnLine[0] , new GeoLocation(wordOnLine[0], Double.parseDouble(wordOnLine[1]), Double.parseDouble(wordOnLine[2]),TimeZone.getTimeZone(wordOnLine[3])));
//locations.add(line);
}
if(file.exists()){
FileInputStream inputFile = openFileInput("au_locations.txt");
input = inputFile;
reader = new BufferedReader((new InputStreamReader((input))));
while ((line = reader.readLine()) != null) {
// builder.append(line).append("\n");
String[] wordOnLine = line.split(",");
geo.put(wordOnLine[0] , new GeoLocation(wordOnLine[0], Double.parseDouble(wordOnLine[1]), Double.parseDouble(wordOnLine[2]),TimeZone.getTimeZone(wordOnLine[3])));
//locations.add(line);
}
}
// return locations;
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
public void AddLocationHandler() throws IOException
{
String name = ((EditText) findViewById(R.id.nameText)).getText().toString();
String longi = ((EditText) findViewById(R.id.longText)).getText().toString();
String lati = ((EditText) findViewById(R.id.latText)).getText().toString();
String timezone = ((EditText) findViewById(R.id.timeText)).getText().toString();
Double locationLong;
Double loctaionLat;
TimeZone locationTimeZone;
try {
loctaionLat = parseDouble(lati);
}catch (NumberFormatException e)
{
Toast toast = Toast.makeText(getApplicationContext(), "not a valid latitude ", Toast.LENGTH_SHORT);
toast.show();
return;
}
try {
locationLong = parseDouble(longi);
}catch (NumberFormatException e)
{
Toast toast = Toast.makeText(getApplicationContext(), "not a valid longitude ", Toast.LENGTH_SHORT);
toast.show();
return;
}
if(timezone.matches("(\\+|\\-)[0-1][0-9]\\:[034][05]")){
locationTimeZone = TimeZone.getTimeZone("GMT" + timezone);
}
else
{
Toast toast = Toast.makeText(getApplicationContext(), "not a valid Time Zone ", Toast.LENGTH_SHORT);
toast.show();
return;
}
File file = new File("au_location.txt");
if(!file.exists()){
file = new File(getFilesDir(), "au_location.txt");
}
FileOutputStream fos = openFileOutput("au_locations.txt", Context.MODE_APPEND);
OutputStreamWriter f = new OutputStreamWriter(fos);
f.write(name + "," +loctaionLat + "," + locationLong + "," + "GMT" + timezone + "\n");
//fos.write(s.getBytes());
//fos.close();
Toast.makeText(getBaseContext(),"Data Saved", Toast.LENGTH_LONG).show();
f.flush();
f.close();
Toast.makeText(getBaseContext(),"New Location Added", Toast.LENGTH_LONG).show();
}
Related
copy part like this(from date to date) I am trying to copy only a part of .CSV file based on the first column (Start Date and Time) data looks like (2019-01-28 10:22:00 AM) but the user have to put it like this (2019/01/28 10:22:00)
this is for windows, java opencsv , this is what I found but dont do what I need exaclty :
like this:
int startLine = get value1 from column csv ;
int endLine = get value2 from column csv;
public static void showLines(String fileName, int startLine, int endLine) throws IOException {
String line = null;
int currentLineNo = 1;
// int startLine = 20056;//40930;
// int currentLineNo = 0;
File currentDirectory = new File(new File(".").getAbsolutePath());
String fromPath = currentDirectory.getCanonicalPath() + "\\Target\\part.csv";
PrintWriter pw = null;
pw = new PrintWriter(new FileOutputStream(fromPath), true);
//pw.close();
BufferedReader in = null;
try {
in = new BufferedReader (new FileReader(fileName));
//read to startLine
while(currentLineNo<startLine) {
if (in.readLine()==null) {
// oops, early end of file
throw new IOException("File too small");
}
currentLineNo++;
}
//read until endLine
while(currentLineNo<=endLine) {
line = in.readLine();
if (line==null) {
// here, we'll forgive a short file
// note finally still cleans up
return;
}
System.out.println(line);
currentLineNo++;
pw.println(line);
}
} catch (IOException ex) {
System.out.println("Problem reading file.\n" + ex.getMessage());
}finally {
try { if (in!=null) in.close();
pw.close();
} catch(IOException ignore) {}
}
}
public static void main(String[] args) throws FileNotFoundException {
int startLine = 17 ;
int endLine = 2222;
File currentDirectory = new File(new File(".").getAbsolutePath());
try {
showLines(currentDirectory.getCanonicalPath() + "\\Sources\\concat.csv", startLine, endLine);
} catch (IOException e) {
e.printStackTrace();
}
// pw.println();
}
Common CSV format uses a comma as a delimiter, with quotations used to escape any column entry that uses them within the data. Assuming that your column one data is consistent with the format you posted, and that I wouldn't have to bother with quotations marks therefor, you could read the columns as:
public static void main(String[] args) {
//This is the path to the file you are writing to
String targetPath = "";
//This is the path to the file you are reading from
String inputFilePath = "";
String line = null;
ArrayList<String> lines = new ArrayList<String>();
boolean add = false;
String startLine = "2019/01/28 10:22:00";
String endLine = "2019/01/28 10:30:00";
String addFlagSplit[] = startLine.replace("/", "-").split(" ");
String addFlag = addFlagSplit[0] + " " + addFlagSplit[1];
String endFlagSplit[] = endLine.replace("/", "-").split(" ");
String endFlag = endFlagSplit[0] + " " + endFlagSplit[1];
try(PrintWriter pw = new PrintWriter(new FileOutputStream(targetPath), true)){
try (BufferedReader input = new BufferedReader(new FileReader(inputFilePath))){
while((line = input.readLine()) != null) {
String date = line.split(",")[0];
if(date.contains(addFlag)) {
add = true;
}else if(date.contains(endFlag)) {
break;
}
if(add) {
lines.add(line);
}
}
}
for(String currentLine : lines) {
pw.append(currentLine + "\n");
}
}catch(FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
File currentDirectory = new File(new File(".").getAbsolutePath());
String targetPath = currentDirectory.getCanonicalPath() + "\\Target\\part.csv";
String inputFilePath = currentDirectory.getCanonicalPath() + "\\Sources\\concat.csv";
String line = null;
ArrayList<String> lines = new ArrayList<String>();
boolean add = false;
String startLine = "2019/01/28 10:22:00";
String endLine = "2019/04/06 10:30:00";
try(PrintWriter pw = new PrintWriter(new FileOutputStream(targetPath), true)){
try (BufferedReader input = new BufferedReader(new FileReader(inputFilePath))){
while((line = input.readLine()) != null) {
String date = line.split(",")[0];
if(date.contains(startLine)) {
add = true;
}else if(date.contains(endLine)) {
break;
}
if(add) {
lines.add(line);
}
}
}
for(String currentLine : lines) {
pw.append(currentLine + "\n");
}
}catch(FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}catch(Exception e) {
e.printStackTrace();
}
}
Being a beginner in programing I'm actually writing a program to practice, wich use url.open to download pages on a forum but after 88-90 loops the url.openstream became very slow and slow down all the program's execution and i don't know why. i searched on internet the explanations but not found it.
private Set<utilisateur> arbretemp = new HashSet<utilisateur>();
private ArrayList<String> arbretempString = new ArrayList<String>();
private ArrayList<utilisateur> tempArray = new ArrayList<utilisateur>();
private String lienPartie1;
private String lienPartie2;
private int nbrePage;
private String nom;
--
String temporaire = "";
for (int i = 1; i <= nbrePage; i++) {
String line = "";
String lien = lienPartie1 + i + lienPartie2;
bar.setValue(i);
try {
url = new URL(lien);
is = url.openStream();
br = new BufferedReader(new InputStreamReader(is));
System.out.println("avant while");
while (((line = br.readLine()) != null)) {
System.out.println("debut de while");
if (((line.contains("alt=")) && line.contains("class=\"user-avatar-msg\""))) {
line = line.trim();
String[] temp = line.split("\"");
temporaire = temp[5] + " \r";
temp = temporaire.split("\"");
byte[] test = temporaire.getBytes();
if (!(temporaire.equalsIgnoreCase(""))) {
utilisateur utiltemp = new utilisateur(temporaire);
if (arbretemp.add(utiltemp)) {
} else {
arbretempString.add(temporaire);
}
}
}
}
System.out.println("fin de while");
} catch (MalformedURLException mue) {
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if (is != null)
is.close();
} catch (IOException ioe) {
// nothing to see here
}
}
String s = "page " + i + "/" + nbrePage;
}
System.out.println("fin de boucle");
Iterator it = arbretemp.iterator();
for (utilisateur a : arbretemp) {
// System.out.println(a.nom);
a.ajouterNbrePost(arbretempString);
}
TreeSet<utilisateur> salComp = new TreeSet<utilisateur>(new utilisateurComp());
salComp.addAll(arbretemp);
tempArray.addAll(arbretemp);
tempArray.sort(new utilisateurComp());
}
as you see it's in french but i hope you will understand anyway.
thanks for your reply and reading
I have 2 almost identical methods. But 1 can see my file , another not.It skips the method body with line = null. Dont understand why.
This doesnt work
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public String handleFileUpload(#RequestParam("file") MultipartFile file, Model model) {
if (!file.isEmpty()) {
try {
String path = "d:/" + file.getOriginalFilename();
byte[] bytes = file.getBytes();
BufferedOutputStream stream =
new BufferedOutputStream(new FileOutputStream(new File(path)));
stream.write(bytes);
model.addAttribute("list", addRecordsToBD(path));
stream.close();
} catch (Exception e) {
log.error("Upload failed", e);
}
}
return "show";
}
private List addRecordsToBD(String path) {
String line;
try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
while ((line = reader.readLine()) != null) {
String[] users = line.split(",");
repository.saveAndFlush(new User(users[0], users[1], users[2],
users[3], users[4]));
}
} catch (IOException e) {
System.out.println("Input problems");
}
System.out.println("Inserting done");
return repository.findAll();
}
But this work great
public void addRecordsToBD(String path) {
String line;
try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
while ((line = reader.readLine()) != null) {
String[] users = line.split(",");
System.out.println("User [Name = " + users[0] +
", surname = " + users[1] +
" login = " + users[2] +
" mail = " + users[3] +
" phone = " + users[4] +
"]");
}
} catch (IOException e) {
System.out.println("Input problems");
}
System.out.println("Inserting done");
}
}
Can some one explain me, what's the problem and why this happened ?
I have this problem in my program:
When I do this:
double a = Double.parseDouble(zero);
double b = Double.parseDouble(data);
double c = a+b;
String d = Double.toString(c);
It returns me a String. For example, I have 0.0 in a and 4.0 in b and it returns 0.04.0.
Can someone explain to me why and what I should do instead?
EDITED: Here is my code:
private void WriteMedia(String data) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("writemedia.txt", Context.MODE_PRIVATE));
String zero;
if(ReadMedia().isEmpty() == true)
{
zero = "0.0";
outputStreamWriter.write(zero);
}
else {zero = ReadMedia();}
double a = Double.parseDouble(zero);
double b = Double.parseDouble(data);
double c = a+b;
String d = Double.toString(c);
outputStreamWriter.write(d);
outputStreamWriter.close();
} catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
private String ReadMedia() {
String ret = "";
try {
InputStream inputStream = openFileInput("writemedia.txt");
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
} catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return ret;
}
private void writeToFile(String data) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("estrela.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
WriteMedia(data);
} catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
private String readFromFile() {
String ret = "";
try {
InputStream inputStream = openFileInput("estrela.txt");
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
} catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
WriteMedia(ret);
return ret;
}
The data is a ratingbar, zero is "0" when I start the app and it should save the rating bar to "increment"(don't know the english word). I thought it would be easy but since is like a bug just for me i'll put the tag android studio.
Here is where I call the method:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
rating = ratingbar.getRating();
writeToFile(Double.toString(rating));
writeMyArray(Double.parseDouble(readFromFile()));
writeMyArray(ratingbar.getRating());
button.setText(getText(R.string.obrigado) + "!" + readFromFile() + " " + media(arraydays) + " " + ReadMedia());
}
});
It returns me the "0.0" and the ratingbar together, for example: "0.05.0"
Your problem is not related to types (other than you guessed) and it is not in the code you originally posted.
Instead, you are simply writing 2 numbers to your output stream. The following code writes 0.0:
if(ReadMedia().isEmpty() == true)
{
zero = "0.0";
outputStreamWriter.write(zero);
}
And, in addition to that, the following code writes the result you actually want:
double a = Double.parseDouble(zero);
double b = Double.parseDouble(data);
double c = a+b;
String d = Double.toString(c);
outputStreamWriter.write(d);
i am trying to use this code to replace field and after the replace is done i like to delete the file. But when i replace the file only 1 line was saved. How should i ensure that the other lines will be saved?
public static void main(String[] args){
AddChips();
}
public static void AddChips() {
File oldFile = new File ("players.dat");
File newFile = new File ("tempchips.dat");
BufferedReader br = null;
BufferedWriter bw = null;
ArrayList<String> player = new ArrayList<String>();
try {
br = new BufferedReader(new FileReader(oldFile));
bw = new BufferedWriter(new FileWriter(newFile));
String line;
Scanner read = new Scanner(System.in);
System.out.println("Please Enter Username");
String UserN = read.nextLine();
System.out.println("Please Enter Chips to Add");
String UserCadd = read.nextLine();
while ((line = br.readLine()) != null) {
String[] details = line.split("\\|");
String Username = details[0];
String Password = details[1];
String Chips = details[2];
int totalChips = (Integer.parseInt(UserCadd)+ Integer.parseInt(Chips));
if (Username.equals(UserN)){
line = Username + "|" + Password + "|" + totalChips;
bw.write(line + System.getProperty("line.separator"));
}
//issue is here
br.close();
bw.close();
oldFile.delete();
newFile.renameTo(oldFile);
//AdminMenu();
}
} catch (Exception e) {
return;
} finally {
try {
if(br != null)
br.close();
} catch (IOException e) {
//
}
try {
if(bw != null)
bw.close();
} catch (IOException e) {
//
}
}
}