I have two classes in a Maven project, which contain the same code (except for their name). The code shall later create a new class with Javassist based on a csv-file.
The first one CsvParser is placed in the src/main/java/csvParser package. The second one TestCsvParser is placed in the src/test/java/csvParser package. In both packages the same file assistant.csv is placed.
When I run the one from the main directory (CsvParser) I get a java.lang.NullPointerException but when I run TestCsvParser, placed in the testdirectory the same code works fine.
Why is it like that? (Or do I just not see something? ;) )
CsvParser:
package csvParser;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class CsvParser {
public static void main(String[] args) throws IOException
{
createClass("/assistant.csv");
}
/**
* Create a class from a csv-file.
*/
private static void createClass(String input) throws IOException {
try(BufferedReader stream = new BufferedReader(new InputStreamReader(
CsvParser.class.getResourceAsStream(input))))
{
// Create class based on csv-file.
}
}
}
TestCsvParser:
package csvParser;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class TestCsvParser {
public static void main(String[] args) throws IOException
{
createClass("/assistant.csv");
}
/**
* Create a class from a csv-file.
*/
private static void createClass(String input) throws IOException {
try(BufferedReader stream = new BufferedReader(new InputStreamReader(
TestCsvParser.class.getResourceAsStream(input))))
{
// Create class based on csv-file.
}
}
}
The exception
Exception in thread "main" java.lang.NullPointerException
at java.io.Reader.<init>(Reader.java:78)
at java.io.InputStreamReader.<init>(InputStreamReader.java:72)
at csvParser.CsvParser.createClass(CsvParser.java:19)
at csvParser.CsvParser.main(CsvParser.java:11)
I believe this question is not a duplicate of a question like What is a NullPointerException because:
The NullPointerException occurs based on the location of the class and the resource referred to. So it's more about directory structures and Mavens targetdirectory.
Thanks for your time!
Finally I found the error. I added the assistant.csv beside the two classes (CsvParser and TestCsvParser). But in both cases this file is not added to the target directory.
The reason why it was working in TestCsvParser is an additional assistant.csv in the ../test/resource/ directory. In fact the two conditions which I described missed this fact and therefore you could not reconstruct my error fully. I'm sorry for that.
To have a working example the resource files both for main and test have to placed within the resource folder instead of beside the class.
Thanks for your help, especially Kalaiselvan A.
It will depend on location of "/assistant.csv" file and if it's not found, you will get NPE. The path will be dependent on your class location since you are calling CsvParser.class.getResourceAsStream..
Related
I have this simple code snippet which throws:
Exception in thread "main" java.lang.ClassCastException: org.eclipse.emf.ecore.xmi.impl.XMIResourceImpl cannot be cast to org.eclipse.emf.ecore.resource.Resource$Factory
relevant code:
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.xmi.impl.XMIResourceImpl;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.Resource;
public class Graphe {
public static void main(String[] args) {
org.eclipse.emf.ecore.resource.Resource.Factory.Registry reg=org.eclipse.emf.ecore.resource.Resource.Factory.Registry.INSTANCE;
Map<String, Object> myMap=reg.getExtensionToFactoryMap();
myMap.put("graphes", new XMIResourceImpl());
ResourceSet resSet=new ResourceSetImpl();
Resource res= resSet.getResource(URI.createURI("My.graphes"), true);//exception here
}
}
the second line is throwing the exception.
My.Graphes is a plugin that I created with EMF and exported it to eclipse host repository. Any help would be so much appreciated
The exception you are experiencing is due to the fact that the getExtensionToFactoryMap deals with Factory as map value, and not Resource. It maps the extension of your URI to a Resource Factory that will create the right Resource.
To deal with your issue, you simply need to register the XMIResourceFactoryImpl instead of the XMIResourceImpl:
myMap.put("graphes", new XMIResourceFactoryImpl());
The following code is for reading or writing files with java, but:
Eclipse prints these errors:
buffer_1 cannot be resolved to a variable
file_reader cannot be resolved
also other attributes...
what is wrong in this code here:
//Class File_RW
package R_2;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.lang.NullPointerException;
public class File_RW {
public File_RW() throws FileNotFoundException, NullPointerException {
File file_to_read = new File("C:/myfiletoread.txt");
FileReader file_reader = new FileReader(file_to_read);
int nr_letters = (int)file_to_read.length()/Character.BYTES;
char buffer_1[] = new char[nr_letters];
}
public void read() {
file_reader.read(buffer_1, 0, nr_letters);
}
public void print() {
System.out.println(buffer_1);
}
public void close() {
file_reader.close();
}
public File get_file_to_read() {
return file_to_read;
}
public int get_nr_letters() {
return nr_letters;
}
public char[] get_buffer_1() {
return buffer_1;
}
//...
}
//main method # class Start:
package R_2;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.lang.NullPointerException;
public class Start {
public static void main(String[] args) {
File_RW file = null;
try {
file = new File_RW();
} catch (NullPointerException e_1) {
System.out.println("File not found.");
}
//...
}
}
I can't find any mistake. I have also tried to include a try catch statement into the constructor of the class "File_RW", but the error messages were the same.
Yes, there are errors in your code - which are of really basic nature: you are declaring variables instead of fields.
Meaning: you have them in the constructor, but they need to go one layer up! When you declare an entity within a constructor or method, then it is a variable that only exists within that constructor/method.
If you want that multiple methods can make use of that entity, it needs to be a field, declared in the scope of the enclosing class, like:
class FileRW {
private File fileToRead = new File...
...
and then you can use your fields within all your methods! Please note: you can do the actual setup within your constructor:
class FileRW {
private File fileToRead;
public FileRW() {
fileToRead = ..
but you don't have to.
Finally: please read about java language conventions. You avoid using "_" within names (just for SOME_CONSTANT)!
javacode already running...thx
same program edited with c++ in visual Studio express...
visit the stackoverflow entry link:
c++ file read write-error: Microsoft Visual C++ Runtime libr..debug Assertion failed, expr. stream.valid()
I have the file allDepartments.json in a subdirectory called fixtures, to which I want to access from the Fixture.java class.
This is my Fixture.java code:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public final class Fixture {
private static final String FIXTURES_PATH = "";
private final String fixture;
public Fixture(String fixtureName) throws IOException {
fixture = new String(Files.readAllBytes(Paths.get(FIXTURES_PATH + fixtureName)));
}
public final String getFixture() {
return fixture;
}
}
However every time he tries to access the file I get a java.nio.file.NoSuchFileException: allDepartments.json...
I have heard of the getResource() method and tried every combination possible of it, without success.
I need this to store multi-line strings for my JUnit tests.
What can I do?
The NIO.2 API can't be used to read files that are effectively project resources, i.e. files present on the classpath.
In your situation, you have a Maven project and a resource that you want to read during the unit test of the application. First, this implies that this resources should be placed under src/test/resources so that Maven adds it automatically to the classpath during the tests. Second, this implies that you can't use the Files utility to read it.
You will need to resort to using a traditional BufferedReader:
public Fixture(String fixtureName) throws IOException {
try (BufferedReader br = new BufferedReader(new InputStreamReader(Fixture.class.getResourceAsStream(FIXTURES_PATH + fixtureName)))) {
// do your thing with br.readLine();
}
}
Note the path given to getResourceAsStream is either relative to the current class or absolute. If the resources is located in src/test/resources/folder/allDepartments.json then a valid path would be /folder/allDepartments.json.
Add allDepartments.json to the.classpath file of the project and java should be able to pick it up.
Refer this topic if you want to know how to add a file to class path from eclipse
when you run Fixtures.java the relative path would be
../fixtures/allDepartments.json
try using this path.
Thank you all for helping and suggestions.
Thanks to you I was able to put things working, so here is the trick (which I guess only works for Maven projects):
I moved the allDepartments.json file to the default src/test/resources folder as suggested by you guys. I didn't even had to modify the pom.xml. And now everything works!
So this is my project structure now:
And the final Fixture.java code is:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.stream.Collectors;
public final class Fixture {
private final String fixture;
public Fixture(String fixtureName) throws IOException {
fixture = this.readFile(fixtureName);
}
private String readFile(String fileName) throws IOException {
final InputStream in = this.getClass().getClassLoader().getResource("fixtures/" + fileName).openStream();
final BufferedReader buffer = new BufferedReader(new InputStreamReader(in));
try {
return buffer.lines().collect(Collectors.joining("\n"));
} finally {
buffer.close();
}
}
public final String getFixture() {
return fixture;
}
}
my first java program ..
so I'm trying to create a file and store in my pc using java
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
public class createfile {
public static void main(String[] args) throws IOException {
int[] numbers = {1,2,3};
for (int item : numbers) {
String key = "file" + item;
File file = File.createTempFile("c:\\",key,".txt");
Writer writer = new OutputStreamWriter(new FileOutputStream(file));
writer.write("abcdefghijklmnopqrstuvwxyz\n");
writer.write("01234567890112345678901234\n");
writer.write("!##$%^&*()-=[]{};':',.<>/?\n");
writer.write("01234567890112345678901234\n");
writer.write("abcdefghijklmnopqrstuvwxyz\n");
writer.close();
}
return file;
}
}
what am I missing here .. I coudln't figured it out. everything seem to follow along the book.
Thanks
===========update ===========
after I took of
- return file ;
- throws IOException ;
- and change to File file = File.createTempFile(key,".txt",new File("c:\\"));
I still get this error
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Unhandled exception type IOException
Unhandled exception type FileNotFoundException
Unhandled exception type IOException
Unhandled exception type IOException
Unhandled exception type IOException
Unhandled exception type IOException
Unhandled exception type IOException
Unhandled exception type IOException
you have some mistakes in java syntax:
When you declare method as void (here public static void main(....)) it means that method has no return value - so line "return file;" not needed here.
Use use wrong signature (wrong parameters types in File.createTempFile function.
Possible usages are:
createTempFile(String prefix, String suffix)
createTempFile(String prefix, String suffix, File directory)
For additional information about File class use this link: http://docs.oracle.com/javase/6/docs/api/java/io/File.html
Following possible version of working code:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
public class createfile
{
public static void main(String[] args) throws IOException
{
int[] numbers = {1,2,3};
for (int item : numbers)
{
String key = "file" + item;
File file = File.createTempFile(key,".txt",new File("c:\\"));
Writer writer = new OutputStreamWriter(new FileOutputStream(file));
writer.write("abcdefghijklmnopqrstuvwxyz\n");
writer.write("01234567890112345678901234\n");
writer.write("!##$%^&*()-=[]{};':',.<>/?\n");
writer.write("01234567890112345678901234\n");
writer.write("abcdefghijklmnopqrstuvwxyz\n");
writer.close();
}
}
}
You can also see another sample how to write text to file: http://www.homeandlearn.co.uk/java/write_to_textfile.html. This link use NetBeans as Java Tool for writing code. I strongly suggest to use some IDE (Eclipse,NetBeans) to write code in java.It will mark your compile mistakes and will suggest corrections.
NetBeans site:https://netbeans.org/
Welcome to Java world
public static void main(String[] args) throws IOException { doesn't return anything, so the return file statement is not required
File.createTempFile either takes String, String, File or String, String so File file = File.createTempFile("c:\\", key, ".txt"); won't compile.
Something like, File file = File.createTempFile(key, ".txt", new File("c:\\")); might be a better idea, but is depended on what you want to achieve.
The JavaDocs state that the prefix must be at least three characters long, so you'll need to pad the key value to meet these requirements.
You MAY find using something like...
File file = new File("C:\\" + key + ".txt");
more managable...
Suppose I do the following in java for a process that stays open:
import java.io.File;
import java.util.Date;
public class LogHolder {
public static void main(String[] args) {
File file1 = new File("myLogFile.log");
while (true) {
System.out.println("Running " + new Date());
}
}
}
Have I locked this file in a way that other windows processes can't write to the log file?
This might help you: FileLock.
No, you haven't locked the file. Here's how the Java documentation summarizes the purpose of java.io.File:
An abstract representation of file and directory pathnames
(In other words, new File() doesn't even open the file.)
You can find the rest here: http://java.sun.com/javase/6/docs/api/java/io/File.html