Olá! EU estou a ter problemas com o java.lang.NullPointerException…
será que me pode ajudar!
O codigo que se segue, funciona quando tabalhando sozinho!
view plaincopy to clipboardprint?
package spimonitoring;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.lang.reflect.Array;
public class InspectionResults44{
public static final byte HEIGHT_AVG_RESULT = 6,
HEIGHT_RANGE_RESULT = 11,
AREA_AVG_RESULT = 16,
AREA_RANGE_RESULT = 22,
VOLUME_AVG_RESULT = 29,
VOLUME_RANGE_RESULT = 28,
HAV_FAILED_FEATURE_RESULT = 35,
REG_OFF_RESULT = 38,
BRIDGE_LEN_RESULT = 41;
private String retrievedData[];
private boolean failed[];
/**
* Constructs this InspectionResult with the data stored in the args.
* This class expects 44 values within the range of the args.
*/
public InspectionResults44(String... args){
retrievedData = args;
boolean temp[] ={
((retrievedData[6].equalsIgnoreCase("F")) ? true: false),//7
((retrievedData[11].equalsIgnoreCase("F")) ? true: false),//12
((retrievedData[16].equalsIgnoreCase("F")) ? true: false),//15
((retrievedData[22].equalsIgnoreCase("F")) ? true: false),//20
((retrievedData[29].equalsIgnoreCase("F")) ? true: false),//23
// ((retrievedData[28].equalsIgnoreCase("F")) ? true: false),//28
// ((retrievedData[35].equalsIgnoreCase("F")) ? true: false),
// ((retrievedData[38].equalsIgnoreCase("F")) ? true: false),
// ((retrievedData[41].equalsIgnoreCase("F")) ? true: false)
};
failed = temp;
}
static class MyArrays{
public static <T> T[] copyOfRange(T[] array, T[] emptyArray, int from, int size){
ArrayList<T> temp = new ArrayList<T>(0);
for(int i = from; i < size; i++){
temp.add(array[i]);
}
return temp.toArray(emptyArray);
}
}
public static void main(String... args){
String line = null;
String Height = null;
String Area = null;
String Volume = null;
String RegOffset = null;
String Bridging = null;
int countHeight = 0,
countArea = 0,
countVolume = 0,
countRegOffset = 0,
countBridging = 0;
int countline = 0;
int startAtLineNo = 7;
FileReader fr = null;
BufferedReader br = null;
try{
fr = new FileReader(new File("K:\\Spi5\\240-25-04-B-02-R1.F.T.#10.489a5f8e.spi.csv"));
br = new BufferedReader(fr);
}catch(Exception e){e.printStackTrace();}
String dwArray[][] ={ {""}, {""}, {""} };
try {
while ((line = br.readLine()) != null) {
if (countline >= startAtLineNo) {
for(int i = 0; i < dwArray.length; i++){
String temp[] = null;
try{ temp = br.readLine().split(",");
}
catch(Exception f){f.printStackTrace();
System.exit(1);
};
String empty[] = {};
temp = InspectionResults44.MyArrays.<String>copyOfRange(temp, empty, 1, temp.length);
dwArray[i] = temp;
}
InspectionResults44 ir[] =
{
new InspectionResults44(dwArray[0]),
new InspectionResults44(dwArray[1]),
new InspectionResults44(dwArray[2])
};
System.out.println(ir[1]); // as an example
spacer(1);
try{
System.out.println(ir[0].hasFailed(InspectionResults32.HEIGHT_AVG_RESULT));
System.out.println(ir[0].getAdjacentValue(InspectionResults32.HEIGHT_AVG_RESULT));
System.out.println(ir[0].hasFailed(InspectionResults32.AREA_AVG_RESULT));
System.out.println(ir[0].getAdjacentValue(InspectionResults32.AREA_AVG_RESULT));
System.out.println(ir[0].hasFailed(InspectionResults32.VOLUME_AVG_RESULT));
System.out.println(ir[0].getAdjacentValue(InspectionResults32.VOLUME_AVG_RESULT));
System.out.println(ir[0].hasFailed(InspectionResults32.REG_OFF_RESULT));
System.out.println(ir[0].getAdjacentValue(InspectionResults32.REG_OFF_RESULT));
System.out.println(ir[0].hasFailed(InspectionResults32.BRIDGE_LEN_RESULT));
System.out.println(ir[0].getAdjacentValue(InspectionResults32.BRIDGE_LEN_RESULT));
}catch(Exception e){
System.out.println(e);
}
}countline++;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void spacer(int lines){
for(int i = 0; i < lines; i++)
System.out.println();
}
/**
* Returns true if the given value has failed, returns false otherwise.
* It's preferred to use the constants defined within this class to get the
* desired information, and not regular ints.
*/
public boolean hasFailed(byte result) throws Exception{
switch(result){
case HEIGHT_AVG_RESULT:
return failed[0];
case HEIGHT_RANGE_RESULT:
return failed[1];
case AREA_AVG_RESULT:
return failed[2];
case AREA_RANGE_RESULT:
return failed[3];
case VOLUME_AVG_RESULT:
return failed[4];
case VOLUME_RANGE_RESULT:
return failed[5];
case HAV_FAILED_FEATURE_RESULT:
return failed[6];
case REG_OFF_RESULT:
return failed[7];
case BRIDGE_LEN_RESULT:
return failed[8];
default :
throw new Exception("Attempt to access invalid result type! Use the Result Constants to avoid this error!");
}
}
/**
* Returns the value next to the specified result.
*/
public String getAdjacentValue(byte result) throws Exception{
if(result >= 0 && result < retrievedData.length - 1)
return retrievedData[result + 1];
else throw new Exception("Error! Attempt to access column with either no adjacent value or outside of data-range!");
}
/**
* Simply returns a String representing the data for each value in this class.
*/
@Override
public String toString(){
String temp = "";
for(String element : retrievedData){
if(element.toString() != retrievedData[retrievedData.length - 1])
temp += element + ", ";
else temp += element;
}
return temp;
}
}
agora num metodo recursivo… está a dar erro null pointer…
eis o codigo
view plaincopy to clipboardprint?
public void listRecursively(File fdir, int depth) throws IOException {
/*Transform milliseconds time to gregorian time */
long datefiles = fdir.lastModified();
SimpleDateFormat Date = new SimpleDateFormat (" dd/MM/yyyy , HH:mm:ss aaa");
Date nDate = new Date(datefiles);
String F = ",F,";
String Height = null;
String Area = null;
String Volume = null;
String RegOffset = null;
String Bridging = null;
String line = null;
int countline = 0;
int startAtLineNo = 7;
int count = 0;
int countHeight = 0,
countArea = 0,
countVolume = 0,
countRegOffset = 0,
countBridging = 0;
/*Line counter*/
try
{
RandomAccessFile File = new RandomAccessFile(fdir,"r");
long lastline=File.length();
File.close();
FileReader fileRead = new FileReader(fdir);
BufferedReader bufferReader = new BufferedReader(fileRead);
String dwArray[][] ={ {""}, {""}, {""} };
Scanner scan = new Scanner(fdir);
while(scan.hasNextLine())
{
if(scan.nextLine().contains(F))
count++;
}
fileRead.close();
bufferReader.close();//___________________________original
InspectionResults44 inspectionResults = new InspectionResults44(line.split(","));
while ((line = bufferReader.readLine()) != null) {
if (countline >= startAtLineNo) {
if (line.split(",").length == 32){
HEIGHT_AVG_RESULT = 6;
AREA_AVG_RESULT = 11;
VOLUME_AVG_RESULT = 16;
REG_OFF_RESULT = 22;
BRIDGE_LEN_RESULT = 29;
}else{//File with 44
HEIGHT_AVG_RESULT = 7;
HEIGHT_RANGE_RESULT = 12;
AREA_AVG_RESULT = 15;
AREA_RANGE_RESULT = 20;
VOLUME_AVG_RESULT = 23;
VOLUME_RANGE_RESULT = 28;
HAV_FAILED_FEATURE_RESULT = 35;
REG_OFF_RESULT = 38;
BRIDGE_LEN_RESULT = 41;
}
try {
if(inspectionResults.hasFailed(InspectionResults44.HEIGHT_AVG_RESULT)){
Height = inspectionResults.getAdjacentValue(InspectionResults44.HEIGHT_AVG_RESULT);
countHeight++;
}
if(inspectionResults.hasFailed(InspectionResults44.AREA_AVG_RESULT)){
Area = inspectionResults.getAdjacentValue(InspectionResults44.AREA_AVG_RESULT);
countArea++;
}
if(inspectionResults.hasFailed(InspectionResults44.VOLUME_AVG_RESULT)){
Area = inspectionResults.getAdjacentValue(InspectionResults44.VOLUME_AVG_RESULT);
countVolume++;
}
if(inspectionResults.hasFailed(InspectionResults44.REG_OFF_RESULT)){
Area = inspectionResults.getAdjacentValue(InspectionResults44.REG_OFF_RESULT);
countRegOffset++;
}
if(inspectionResults.hasFailed(InspectionResults44.BRIDGE_LEN_RESULT)){
Area = inspectionResults.getAdjacentValue(InspectionResults44.BRIDGE_LEN_RESULT);
countBridging++;
}}
catch (Exception e) {
e.printStackTrace();
}
fileRead.close();
bufferReader.close();
}}
/* Output1 */
if (fdir.getPath().endsWith(".csv") /*&& fdir.lastModified() > HostFile.lastModified()*/)
System.out.println(INDENTS[depth] + x +", "+fdir.getName() +", "+ count +","+Date.format(nDate) + "," + countHeight + "," + countArea + "," + countVolume + "," + countRegOffset + "," + countBridging);
/* Output2 */
if (fdir.getPath().endsWith(".csv") /*&& fdir.lastModified() > HostFile.lastModified()*/)
fw.write( INDENTS[depth] + x +", "+ fdir.getName() +", "+ count +","+ Date.format(nDate)+ System.getProperty("line.separator"));
fw.flush();
//if (fdir.getPath().endsWith(".csv") && (fdir.length()/512 )>= 1 && fdir.length()/512 <= 3)
}
catch(IOException e){
}
if (fdir.isDirectory() && !fdir.isHidden() && depth < MAX_DEPTH) {
for (File f : fdir.listFiles()){ // Go over each file/subdirectory.
listRecursively(f, depth+1);
}}}
o codigo recursivo por sua vez é utilizado da seguinte forma…
/* ---------------------SPI01----------------------- */
/*Creates the Object file SPI1.log */
//outputFrame.aTextArea.setText("");
File f1 = new File("E:\\public\\Log\\Log\\SPI01.log");
if(f1.exists())
//System.out.println("Log File SPI01..................................... Done;");
setMessage("Log File SPI01..................................... Done;");
/* if it doesn't exists */
if(!f1.exists())
//System.out.println("The Log file does not exist");
setMessage("The Log file does not exist");
/* New file ... exception popup */
try {
if(f1.createNewFile())
//System.out.println("Log file created.................................. Done;");
setMessage("Log file created.................................. Done;");
}
catch (IOException e) {
//System.out.println("I/O Error");
setMessage("I/O Error");
}
/*Creates the Object file LD01.log */
File ff1 = new File("E:\\public\\Log\\LotData\\LD01.log");
if(ff1.exists())
//System.out.println("LotData SPI01..................................... done;");
setMessage("LotData SPI01..................................... done;");
/* if it doesn't exists */
if(!ff1.exists()){
setMessage("The LotData file does not exist");
//System.out.println("The LotData file does not exist");
/* New file ... exception popup */
try {
if(ff1.createNewFile())
//System.out.println("LotData file created.................................. done;");
setMessage("LotData file created.................................. done;");
}
catch (IOException e) {
//System.out.println("I/O Error");
setMessage("I/O Error");
}
}
/* mapping */
/* Creates a temporary Network Drive before starting the cycle */
String mapSPI01 = new String("net use z: \\\\172.21.34.1\\d$ qmy001 /user:172.21.34.1\\administrator /Persistent:No");
Runtime rt = Runtime.getRuntime();
try {
Process con = rt.exec(mapSPI01);
con.waitFor();
//System.out.println("Drive mapping Spi 01......................... Done");
setMessage("Drive mapping Spi 01......................... Done");
}
catch (IOException e) {
System.out.println(e);
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*Copy LotData contents from d:\DataLot\LotData.csv to the Respective LD.log*/
try {
if (LotInput.isDirectory()) {
//fos = new FileOutputStream(HostFileLD01);
files = LotInput.listFiles();
xw = new FileWriter(HostFileLD01);
for (int i = 0; i < files.length; i++) {
file = files[i];
fr = new FileReader(file);
br = new BufferedReader(fr);
x=1;
while ((line = br.readLine()) != null) {
//System.out.println(line);
xw.write(x+","+line + System.getProperty("line.separator")) ;//change line
xw.flush();
}
}
}
}
catch (FileNotFoundException fnex) {
fnex.printStackTrace();
}
catch (IOException ioex) {
ioex.printStackTrace();
}
/*end of copy*/
setMessage("Collecting Data from SPI 01");
/* Scanning */
//File root = new File("z:\\SE300 Output");
File root = new File("K:\\Spi5");
if (root != null && root.isDirectory()) {
try{
fw = new FileWriter("E:\\public\\Log\\Log\\SPI01.log");
x=5;
listRecursively(root, 0);
fw.close();
}
catch(NullPointerException np){
np.printStackTrace();
}
catch(IOException exc){
exc.printStackTrace();
}
}
else
{
//System.out.println("Not a directory: " + root);
setMessage("Not a directory: " + root);}
/* Deletes temporary Network Drive before finishing the cycle */
try
{
String[] cmd = new String[3];
cmd[0] = "cmd.exe" ;
cmd[1] = "/C" ;
cmd[2] = "net use z: /delete /y";
Runtime rtoff = Runtime.getRuntime();
//System.out.println("Executing " + cmd[0] + " " + cmd[1]
// + " " + cmd[2]);
setMessage("Executing " + cmd[0] + " " + cmd[1]
+ " " + cmd[2]);
Process proc = rtoff.exec(cmd);
// any error message?
StreamGobbler1 errorGobbler = new
StreamGobbler1(proc.getErrorStream(), "ERROR");
// any output?
StreamGobbler1 outputGobbler = new
StreamGobbler1(proc.getInputStream(), "OUTPUT");
// kick them off
errorGobbler.start();
outputGobbler.start();
// any error???
int exitVal = proc.waitFor();
setMessage("ExitValue: " + exitVal);
} catch (Throwable t)
{
t.printStackTrace();
}
/* ---------------------SPI01----------------------- */
/*Creates the Object file SPI1.log */
//outputFrame.aTextArea.setText("");
File f1 = new File("E:\\public\\Log\\Log\\SPI01.log");
if(f1.exists())
//System.out.println("Log File SPI01..................................... Done;");
setMessage("Log File SPI01..................................... Done;");
/* if it doesn't exists */
if(!f1.exists())
//System.out.println("The Log file does not exist");
setMessage("The Log file does not exist");
/* New file ... exception popup */
try {
if(f1.createNewFile())
//System.out.println("Log file created.................................. Done;");
setMessage("Log file created.................................. Done;");
}
catch (IOException e) {
//System.out.println("I/O Error");
setMessage("I/O Error");
}
/*Creates the Object file LD01.log */
File ff1 = new File("E:\\public\\Log\\LotData\\LD01.log");
if(ff1.exists())
//System.out.println("LotData SPI01..................................... done;");
setMessage("LotData SPI01..................................... done;");
/* if it doesn't exists */
if(!ff1.exists()){
setMessage("The LotData file does not exist");
//System.out.println("The LotData file does not exist");
/* New file ... exception popup */
try {
if(ff1.createNewFile())
//System.out.println("LotData file created.................................. done;");
setMessage("LotData file created.................................. done;");
}
catch (IOException e) {
//System.out.println("I/O Error");
setMessage("I/O Error");
}
}
/* mapping */
/* Creates a temporary Network Drive before starting the cycle */
String mapSPI01 = new String("net use z: \\\\172.21.34.1\\d$ qmy001 /user:172.21.34.1\\administrator /Persistent:No");
Runtime rt = Runtime.getRuntime();
try {
Process con = rt.exec(mapSPI01);
con.waitFor();
//System.out.println("Drive mapping Spi 01......................... Done");
setMessage("Drive mapping Spi 01......................... Done");
}
catch (IOException e) {
System.out.println(e);
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*Copy LotData contents from d:\DataLot\LotData.csv to the Respective LD.log*/
try {
if (LotInput.isDirectory()) {
//fos = new FileOutputStream(HostFileLD01);
files = LotInput.listFiles();
xw = new FileWriter(HostFileLD01);
for (int i = 0; i < files.length; i++) {
file = files[i];
fr = new FileReader(file);
br = new BufferedReader(fr);
x=1;
while ((line = br.readLine()) != null) {
//System.out.println(line);
xw.write(x+","+line + System.getProperty("line.separator")) ;//change line
xw.flush();
}
}
}
}
catch (FileNotFoundException fnex) {
fnex.printStackTrace();
}
catch (IOException ioex) {
ioex.printStackTrace();
}
/*end of copy*/
setMessage("Collecting Data from SPI 01");
/* Scanning */
//File root = new File("z:\\SE300 Output");
File root = new File("K:\\Spi5");
if (root != null && root.isDirectory()) {
try{
fw = new FileWriter("E:\\public\\Log\\Log\\SPI01.log");
x=5;
listRecursively(root, 0);
fw.close();
}
catch(NullPointerException np){
np.printStackTrace();
}
catch(IOException exc){
exc.printStackTrace();
}
}
else
{
//System.out.println("Not a directory: " + root);
setMessage("Not a directory: " + root);}
/* Deletes temporary Network Drive before finishing the cycle */
try
{
String[] cmd = new String[3];
cmd[0] = "cmd.exe" ;
cmd[1] = "/C" ;
cmd[2] = "net use z: /delete /y";
Runtime rtoff = Runtime.getRuntime();
//System.out.println("Executing " + cmd[0] + " " + cmd[1]
// + " " + cmd[2]);
setMessage("Executing " + cmd[0] + " " + cmd[1]
+ " " + cmd[2]);
Process proc = rtoff.exec(cmd);
// any error message?
StreamGobbler1 errorGobbler = new
StreamGobbler1(proc.getErrorStream(), "ERROR");
// any output?
StreamGobbler1 outputGobbler = new
StreamGobbler1(proc.getInputStream(), "OUTPUT");
// kick them off
errorGobbler.start();
outputGobbler.start();
// any error???
int exitVal = proc.waitFor();
setMessage("ExitValue: " + exitVal);
} catch (Throwable t)
{
t.printStackTrace();
}
Obrigado desde já…