I have a Java program that reads from a cvs file that looks like this:
2000;Mall1;8
2002;Mall3;23
2003;Mall4;31
...
I want the program to read from the cvs file into an array and sort the array based on the third column/field.
However, whenever I print the elements of array[2] I get an ArrayIndexOutOfBoundException. I can't see why is this happening since the array's[2] size should be already fixed.
Here is the code:
import java.util.*;
import java.io.*;
public class Prog3
{
public static void main(String[] args)
{
String csvFile = "test.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ";";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
String[] array = line.split(cvsSplitBy);
System.out.println(array[2]);
Arrays.sort(array[2]);
System.out.println("Sorted\n" + Arrays.toString(array[2]));
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (ArrayIndexOutOfBoundsException e)
{
e.printStackTrace();
}
finally {
if (br != null)
{
try
{
br.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
}
Any help is appreciated :)
Related
I am facing some difficulties with testing constructor of my class using JUnit 4.13. What I am trying to do is to test that constructor is throwing FileNotFoundExeption when I pass wrong file name.
This is my constructor (parameter 'file' is name of file where I store languages):
public LanguageManager(String file) {
this.languages = new ArrayList<Language>();
try {
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), "utf-8"));
String line;
while((line = in.readLine()) != null) {
line = line.trim();
if (line.equals("") || line.startsWith("#"))
continue;
Language j = new Language(line);
this.languages.add(j);
}
in.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
This is my function for testing this constructor:
#Test(expected=FileNotFoundException.class)
public void testLanguageManager() {
LanguageManager ajm = new LanguageManager("non_existing_file.txt");
}
I suspect that there is problem with try catch block in constructor but can't figure out what I am doing wrong. Any help is appreciated.
I am trying to get all the mac and IP from my android using the following code. But the following code only works in java. I want to use it in kotlin so I tried java to kotlin converter. But it didn't work. could anyone tell me how the following part of the code will be used in kotlin:
listNote.clear();
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader("/proc/net/arp"));
String line;
while ((line = bufferedReader.readLine()) != null) {
String[] splitted = line.split(" +");
if (splitted != null && splitted.length >= 4) {
String ip = splitted[0];
String mac = splitted[3];
if (mac.matches("..:..:..:..:..:..")) {
Node thisNode = new Node(ip, mac);
listNote.add(thisNode);
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Auto conversion does not handle your while loop since "Assignments are not expression".
You can work around it by using built-in Readers extension function forEachLine, in which case each line is passed as the only argument to the lambda expression as it:
var bufferedReader: BufferedReader? = null
try {
bufferedReader = BufferedReader(FileReader("/proc/net/arp"))
bufferedReader.forEachLine {
val splitted = it.split(" +".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
if (splitted.size >= 4) {
val ip = splitted[0]
val mac = splitted[3]
if (mac.matches("..:..:..:..:..:..".toRegex())) {
listNote.add(Node(ip, mac))
}
}
}
} catch (e: IOException) {
e.printStackTrace()
} finally {
try {
bufferedReader?.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
You can also remove FileNotFoundException since it's a subclass of IOException, and catch block is the same.
Goal: Print the data from a .dat file to the console using Eclipse.
(Long-Term Goal): Executable that I can pass a .dat file to and it creates a new txt file with the data formatted.
The .dat: I know the .dat file contains control points that I will need to create a graph with using ECMAScript.
Eclipse Setup:
Created Java Project
New > Class .. called the Class FileRead
Now I have FileRead.java which is:
1/ package frp;
2/
3/ import java.io.BufferedReader;
4/ import java.io.File;
5/ import java.io.FileReader;
6/
7/ public class FileRead {
8/
9/ public static void main(String[] args) {
10/ FileReader file = new FileReader(new File("dichromatic.dat"));
11/ BufferedReader br = new BufferedReader(file);
12/ String temp = br.readLine();
13/ while (temp != null) {
14/ temp = br.readLine();
15/ System.out.println(temp);
16/ }
17/ file.close();
18/ }
19/
20/ }
Please note this approach was borrowed from here: https://stackoverflow.com/a/18979213/3306651
1st Challenge: FileNotFoundException on LINE 10
Screenshot of Project Explorer:
QUESTION: How to correctly reference the .dat file?
2nd Challenge: Unhandled exception type IOException LINES 12, 14, 17
QUESTION: How to prevent these exceptions?
Thank you for your time and effort to help me, I am recreating Java applets using only JavaScript. So, I'm looking to create java tools that extract data I need to increase productivity. If you are interested in phone/web app projects involving JavaScript, feel free to contact me 8503962891
1. Without changing your code, you must place the file in the project's root folder.
Otherwise, reference it as src/frp/dichromatic.dat
2. Doing something like this:
public static void main(String[] args) {
FileReader file = null;
try {
file = new FileReader(new File("dichromatic.dat"));
} catch (FileNotFoundException e1) {
System.err.println("File dichromatic.dat not found!");
e1.printStackTrace();
}
BufferedReader br = new BufferedReader(file);
String line;
try {
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.err.println("Error when reading");
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
System.err.println("Unexpected error");
e.printStackTrace();
}
}
}
}
3. Creation of a new txt file "formatted". In this example, the formatting will be settings the characters to uppercase.
public static void main(String[] args) {
FileReader file = null;
BufferedWriter bw = null;
File outputFile = new File("output.formatted");
try {
file = new FileReader(new File("dichromatic.dat"));
} catch (FileNotFoundException e1) {
System.err.println("File dichromatic.dat not found!");
e1.printStackTrace();
}
try {
bw = new BufferedWriter(new FileWriter(outputFile));
} catch (IOException e1) {
System.err.println("File is not writtable or is not a file");
e1.printStackTrace();
}
BufferedReader br = new BufferedReader(file);
String line;
String lineformatted;
try {
while ((line = br.readLine()) != null) {
lineformatted = format(line);
bw.write(lineformatted);
// if you need it
bw.newLine();
}
} catch (IOException e) {
System.err.println("Error when processing the file!");
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
System.err.println("Unexpected error");
e.printStackTrace();
}
}
if (bw != null) {
try {
bw.close();
} catch (IOException e) {
System.err.println("Unexpected error");
e.printStackTrace();
}
}
}
}
public static String format(String line) {
// replace this with your needs
return line.toUpperCase();
}
I would strongly recommend spending some time reading through the Java Trails Tutorials. To answer your specific question, look at Lesson: Exceptions.
To oversimplify, just wrap the file-handling code in a try...catch block. By example:
package frp;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
public class FileRead {
public static void main(String[] args) {
try {
FileReader file = new FileReader(new File("dichromatic.dat"));
BufferedReader br = new BufferedReader(file);
String temp = br.readLine();
while (temp != null) {
temp = br.readLine();
System.out.println(temp);
}
file.close();
} catch (FileNotFoundException fnfe) {
System.err.println("File not found: " + fnfe.getMessage() );
} catch (IOException ioe) {
System.err.println("General IO Error encountered while processing file: " + ioe.getMessage() );
}
}
}
Note that ideally, your try...catch should wrap the smallest possible unit of code. So, wrap the FileReader separately, and "fail-fast" if the file isn't found, and wrap the readLine loop in its own try...catch. For more examples and a better explanation of how to deal with exceptions, please reference the link I provided at the top of this answer.
Edit: issue of file path
Not finding the file has to do with the location of the file relative to the root of the project. In your original post, you reference the file as "dichromatic.dat" but relative to the project root, it is in "src/frp/dichromatic.dat". As rpax recommends, either change the string that points to the file to properly reference the location of the file relative to the project root, or move the file to project root and leave the string as-is.
I have a class with this code
public boolean busybox() throws IOException
{
try
{
Process p =Runtime.getRuntime().exec("busybox");
InputStream a = p.getInputStream();
InputStreamReader read = new InputStreamReader(a);
BufferedReader in = new BufferedReader(read);
StringBuilder buffer = new StringBuilder();
String line = null;
try {
while ((line = in.readLine()) != null) {
buffer.append(line);
}
} finally {
read.close();
in.close();
}
String result = buffer.toString().substring(0, 15);
System.out.println(result);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
In another class I have this code
try {
if(root.busybox()) {
Busybox.setText(Html.fromHtml((getString(R.string.busybox))));
}
else {
Busybox.setText(Html.fromHtml((getString(R.string.no))));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
If I want to write in this TextView the outpout generated by System.out.println(result);
How can i do? Thanks in advance! I made several attempts, but I have several errors and the code is wrong.
change return type of public boolean busybox() to string like public String busybox() and return result.
then use
try {
String myResult=root.busybox();
if(myResult!=null&&myResult.length>0) {
Busybox.setText(Html.fromHtml((myResult)));
}
else {
Busybox.setText(Html.fromHtml((getString(R.string.no))));
}
}
I have developed a java code in eclipse.My code reads data from a .txt file by using server_ip. I have created an executable jar file of the code and then created an .exe file using launch4j. The .exe file shows data if I run it in my laptop,but it does not show any data if I run it in other pc. then it shows null point exception. my operating system is windows 7-32 bit. I am giving my code here. please give me solutions.
package remotedata;
import java.awt.*;
import java.net.;
import java.io.;
public class remotedataread extends Frame
{
public static void main(String[] args)
throws InterruptedException, IOException{
BufferedReader br = null;
TextArea FileText =
new TextArea(" Content of the File \'temp1.txt\' :");
try
{
URL url =
new URL("file://server_ip/path_file.txt");
InputStream is = url.openStream();
br = new BufferedReader(new InputStreamReader(is));
/* String line = null;
while (true) {
line = br.readLine();
if (line == null) {
//wait until there is more of the file for us to read
Thread.sleep(1000);
}
else {
System.out.println(line);
}
}*/
}
catch (MalformedURLException e)
{
System.out.println("Bad URL");
}
catch (IOException e)
{
System.out.println("IO Error : "+e.getMessage());
}
FileText.setBackground(Color.white);
FileText.append(String.valueOf('\n'));
Frame f = new Frame("server data");
f.setSize(200,200);
f.add(FileText);
f.setVisible(true);
try
{
String s;
s=null;
boolean eof = false;
//while (true) {
s = br.readLine();
System.out.println("Time Temperature");
while( !eof )
{
FileText.append(s + String.valueOf('\n'));
try
{
s = br.readLine();
if ( s == null )
{
// eof = true;
// br.close();
Thread.sleep(1000);
}
else{
//System.out.println("Time Temperature");
System.out.println(s);
}
}
catch (EOFException eo)
{
eof = true;
}
catch (IOException e)
{
System.out.println("IO Error : "+e.getMessage());
}
}
//}
}
catch (IOException e)
{
System.out.println("IO Error : "+e.getMessage());
}
}
}
Maybe , you're application is not able to connect to the other node ..hence its throwing a NullPointer exception .Make sure that computers are in the Network
your prolem seems to be here:
URL url =
new URL("file://server_ip/path_file.txt");
InputStream is = url.openStream();
br = new BufferedReader(new InputStreamReader(is));
the url "file://server_ip/path_file.txt" is valid on your laptop, but not on other pc's