Project java NullPointerException when trying to read a csv file - java

I have a csv file that my class with the code below is trying to read that data to use in my project, but when i run the project, I have a NullPointerException like the csv file is null, but he isn't. The path of the csv file is right and apparently I don't have any error in my class too, what I am missing?
package main.java.br.com.quantumfinance.selecaoEstagio.leitor;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class LeitorDeArquivo {
public List<String> lerArquivo() {
try (InputStream resourceAsStream = LeitorDeArquivo.class.getResourceAsStream("/acoes.csv")) {
// Leitura do arquivo.
BufferedReader br = new BufferedReader(new InputStreamReader(resourceAsStream));
// ignora a primeira linha
br.readLine();
List<String> cotacoes = new ArrayList<>();
String linha;
while ((linha = br.readLine()) != null) {
cotacoes.add(linha);
}
return cotacoes;
} catch (FileNotFoundException e) {
System.out.println("Arquivo n�o encontrado.");
e.printStackTrace();
} catch (IOException e) {
System.out.println("Erro de IO.");
e.printStackTrace();
}
throw new RuntimeException("Erro na leitura do arquivo, consulte o console para maiores detalhes.");
}
}
This is the error that I receive when trying to run the project
Exception in thread "main" java.lang.NullPointerException
at java.base/java.io.Reader.<init>(Reader.java:168)
at java.base/java.io.InputStreamReader.<init>(InputStreamReader.java:76)
at main.java.br.com.quantumfinance.selecaoEstagio.leitor.LeitorDeArquivo.lerArquivo(LeitorDeArquivo.java:17)
at main.java.Questoes.main(Questoes.java:26)
This is the project structure

Related

Recording keyboard, mouse activity in linux

I need some way to detect mouse/keyboard activity on Linux. I need to record this activity and send this record to my android tablet using tcp socket. I m running this program in terminal and it is showing error Exception in thread "main"java.lang.UnsupportedClassVersionError: Mouse : Unsupported major.minor version 51.0..any help????
import java.awt.HeadlessException;
import java.awt.MouseInfo;
import java.awt.Point;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Timer;
import java.util.TimerTask;
public class Mouse {
public static void main(String[] args) throws InterruptedException {
Point p, prev_p;
p = MouseInfo.getPointerInfo().getLocation();
DatagramSocket socket = null;
try {
socket = new DatagramSocket(8988);
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InetAddress addr = null;
try {
addr = InetAddress.getByName("107.108.203.204");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
File file = new File("/sys/kernel/debug/usb/usbmon/6u");
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(file));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
System.err
.println("To fix the error Run as root or Change ownership of the file to the user who runs this program");
}
String line, s = null;
try {
while ((line = br.readLine()) != null) {
prev_p = p;
p = MouseInfo.getPointerInfo().getLocation();
String[] arr = line.split(" ");
if (arr.length == 8)
s = arr[7];
System.out.println(s+" "+Integer.parseInt(s.substring(2,4),16));
byte[] buffer = s.getBytes();
DatagramPacket pak = new DatagramPacket(buffer, buffer.length,
addr, 8988);
try {
socket.send(pak);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I shall not go into the basics of telling you how to use a tcp socket, that is simple enough.
However the basics of your question is that you will need to open and constantly read the /dev/input/by-id/yourmouseorkeyboardnamehere file. Reading this file will cause your program to block until there is a keyboard/mouse input (depending on if you read the keyboard or mouse file) then you will be able to read data representing what data came from the keyboard or mouse.
It should from there be fairly easy to send this data over a tcp socket to your tablet, you can learn to do that from any sockets tutorial on the Internet.
If you have any questions or need more detail please comment bellow.

file cannot be deleted even after closing streams

I'm trying to open a file from a URL, copy it to a temporary file, and then delete the temporary file when processing work is done. However, I am unable to delete the file. I have tried closing all streams, I have tried deleting with both deleteOnExit() method and the Delete() method. This is an excel file which I am working with. When I am not using an excel file, or more particularly the Workbook object as shown in my code below, the file deletes just fine. As soon as I pass my file to the workbookFactory.create() method, my file cannot be deleted by the code.
Here's the code below:
public class URLtoFileWriting {
/**
* #param args the command line arguments
* #throws java.io.IOException
*/
static File destinationFile;
public static void getFile() throws IOException {
try {
// TODO code application logic here
URL fileURL = new URL("http://www.testURL.com/testfile.xlsx");
URLtoFileWriting.destinationFile = File.createTempFile("remotefile",".xlsx");
try {
URLConnection URLconnection = fileURL.openConnection();
InputStream inputStream = URLconnection.getInputStream();
FileOutputStream fileoutputStream = new FileOutputStream(URLtoFileWriting.destinationFile);
IOUtils.copy(inputStream, fileoutputStream);
Workbook wb = WorkbookFactory.create(URLtoFileWriting.destinationFile);
System.out.println(URLtoFileWriting.destinationFile.getAbsolutePath());
inputStream.close();
fileoutputStream.close();
System.out.println("Deleted testWB?!" + URLtoFileWriting.destinationFile.delete());
} catch (IOException ex) {
Logger.getLogger(URLtoFileWriting.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidFormatException ex) {
Logger.getLogger(URLtoFileWriting.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (MalformedURLException ex) {
Logger.getLogger(URLtoFileWriting.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
All the imports I am using:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.io.IOUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
I suspect it has something to do with the workbookFactory.create() method, as deletion becomes impossible once I have passed the file to this method.
What am I doing wrong here?
UPDATE. I have come across a fix:
You can pass the File to a FileInputStream, and then pass this stream to the WorkbookFactory.Create() method.
Updated code below to reflect this:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.io.IOUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class URLtoFileWriting {
/**
* #param args the command line arguments
* #throws java.io.IOException
*/
static File destinationFile;
public static void getFile() throws IOException {
try {
// TODO code application logic here
URL fileURL = new URL("http://www.testURL.com/testfile.xlsx");
URLtoFileWriting.destinationFile = File.createTempFile("remotefile",".xlsx");
try {
URLConnection URLconnection = fileURL.openConnection();
InputStream inputStream = URLconnection.getInputStream();
FileOutputStream fileoutputStream = new FileOutputStream(URLtoFileWriting.destinationFile);
IOUtils.copy(inputStream, fileoutputStream);
FileInputStream FIS = new FileInputStream(URLtoFileWriting.destinationFile);
Workbook wb = WorkbookFactory.create(FIS);
FIS.close();
inputStream.close();
fileoutputStream.close();
System.out.println(URLtoFileWriting.destinationFile);
System.out.println(URLtoFileWriting.destinationFile.delete());
} catch (IOException ex) {
Logger.getLogger(URLtoFileWriting.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidFormatException ex) {
Logger.getLogger(URLtoFileWriting.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (MalformedURLException ex) {
Logger.getLogger(URLtoFileWriting.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
I hope this helps.
Find the solution here Close Filehandle for Workbook (apache poi).
Use NPOIFSFileSystem#close() or OPCPackage#close().
For more info have a look at the overloaded constructors of WorkbookFactory class.

Generating an xls file from an xml file

I am using the below command to convert an xml file to an excel file, but I could not generate the xls file, please advise how to do that?
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.poi.hssf.model.Workbook;
//import nl.fountain.xelem.excel.Workbook;
import nl.fountain.xelem.lex.ExcelReader;
import org.xml.sax.SAXException;
public class XmlToXls11 {
public void XML() throws ParserConfigurationException, SAXException, IOException
{
ExcelReader reader = new ExcelReader();
Workbook xlWorkbook = (Workbook) reader.getWorkbook("c:/book.xml");
}
}
have you tried the XSerializer?
public void writeExcelXmlFile(String fileNameIn, String fileNameOut){
XLDocument xldoc = new XLDocument(fileNameIn);
OutputStream out;
try {
out = new BufferedOutputStream(new FileOutputStream(fileNameOut));
new XSerializer().serialize(xldoc.getDocument(), out);
out.close();
} catch (XelemException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I guess that it's not possible to write the old xls-binary format with this library.
have a look here:
https://stackoverflow.com/questions/18177870/how-can-i-read-or-write-xls-files-using-java

how to open .mdb from ftp location jackcess

hi all with this code i can successfully download allpg.mdb and displaying...
now i want to save the downloaded file to c:/folder....
if i edit
dbTempFile = File.createTempFile("dbTempFile",".mdb"); to
dbTempFile = File.createTempFile("c:/dbTempFile",".mdb"); than it give : The filename, directory name, or volume label syntax is incorrect error.
i just want to save the downloaded file to any where to my local drive.
here is code:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.net.ftp.FTPClient;
import com.healthmarketscience.jackcess.Database;
import com.healthmarketscience.jackcess.Table;
public class DownloadFile {
public static void main(String[] args) throws Exception {
FTPClient client = new FTPClient();
File dbTempFile=null;
FileOutputStream fileOutputStream = null;
try {
client.connect("ftp.mypak.com");
client.login("myid", "mypwd");
client.setFileType(FTPClient.BINARY_FILE_TYPE);
dbTempFile = File.createTempFile("dbTempFile",".mdb");
fileOutputStream = new FileOutputStream(dbTempFile);
client.retrieveFile("/HASSAN/MDMSTATS/allpg.mdb", fileOutputStream);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (fileOutputStream != null) {
fileOutputStream.close();
System.out.println("got");
Table table = Database.open(dbTempFile).getTable("items");
System.out.println(table.display());
System.out.println("got");
}
client.disconnect();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
You are not giving the right file name to the Jackcess constructor. should be:
Table table = Database.open(dbTempFile).getTable("items");

Error in Writing a text file "Exception in thread "main" " [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Causes of 'java.lang.NoSuchMethodError: main Exception in thread “main”'
I am trying to write a byte array in a text file. It is giving me error:
java.lang.NoSuchMethodError: main
Exception in thread "main"
The code i am using is as under
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
public class writefile {
//it works well
public static void main()throws IOException{
Writer output = null;
byte[] a= {1,2,3,4,5,6};
try {
String text = "abcd...\n";
String str3 = text.concat("the end");
String NL = System.getProperty("line.separator");
str3 = str3.concat(NL);
str3= str3.concat("next line");
for ( int i=0; i < a.length; i++){
str3 = str3.concat(NL);
str3= str3.concat(" " +a[i]);
}
File file = new File("write.txt");
output = new BufferedWriter(new FileWriter(file));
output.write(str3);
System.out.println("Your file has been written");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (output != null) {
output.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Kindly help how can i resolve the problem.
The main method of a Java program must take an argument of type String[] representing the arguments (if any) passed to the program on launch.
the main signature must contain String[] argument

Categories