Read file content from different package in JUnit - java

I am trying to read a file (which contains my data) in my JUnit code.
I have a source folder named "test" and under it are the two packages below
com.junit.codes (JUnit codes)
com.junit.codes.data (csv Files i.e. myData.csv)
My problem is I cant access the files under com.junit.codes.data.
I have tried using classLoader but it does not work.
Can anyone help me with this problem?

Presuming you are using a Maven based setup, do the following:
As non-Java files by default is not copied to the "target" folder in the "compile" phase you should add your csv-file to src/test/resources/com/junit/codes/data
From your test class you should now be able to do getClass().getResourceAsStream("./data/myData.csv") to open an input stream to read the data from.
Example:
package com.junit.codes;
import org.junit.Test;
import java.io.InputStream;
import static org.junit.Assert.assertNotNull;
public class ReadTest {
#Test
public void name() throws Exception {
try(final InputStream inputStream = getClass().getResourceAsStream("./data/myData.csv")) {
assertNotNull(inputStream);
}
}
}

Related

importing a specific class in java

So, I have a package "com", which consists of two sub-packages "Common" and "Model1". The Model1 contains a class Model which I am trying to import in the Servlet2 class, which resides in the Common package. I compile the Model class first which stays fine, but the Servlet2 class doesn't and comes up with an error saying "package com.Model1 doesn't exist"
Here's the Model class:
package com.Model1;
import java.util.*;
**public** class Model{
public ArrayList<String> getBrands(String color){
ArrayList<String> brands=new ArrayList<String>();
if(color.equals("amber")){
brands.add("Jack Amber");
brands.add("Red Moose");
}
else{
brands.add("Jail Pale Ale");
brands.add("Gout Stout");
}
return brands;
}
}
Here's the Servle2 class:
package com.Common;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import com.Model1.Model;
public class Servlet2 extends HttpServlet{
public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println("Coffee selection advice<br>");
String c=req.getParameter("color");
Model m=new Model();
ArrayList result=m.getBrands(c);
out.println("<br>Got coffee color "+c);
Iterator it=result.iterator();
while(it.hasNext()){
out.println("<br> Try: "+it.next());
}
}
}
I just can't seem to figure out how to sort this out.
Edit: Realised that default modifier is restrictive, but even making it public doesn't seem to work.
I am using notepad++ and I hope this works as the Minimal, Complete, and Verifiable example:
package com.common;
import com.model.*;
public class TheClassIWantToImportInto {
public static void main(String[] args){
System.out.println("Testing 1");
TheClassIwantToImport obj=new TheClassIWantToImportInto();
obj.testFunction();
}
}
The second class:
package com.model;
public class TheClassIWantToImport{
public void testFunction(){
System.out.println("testing function");
}
}
Both the .java files are in the same folder "C:\Program Files\Java\jdk1.8.0_161\bin"
Using the following commands in this order:
javac -d . TheClassIWantToImport.java (Works fine)
javac -d . TheClassIWantToImportInto.java (Error: package com.model doesn't exist)
Set up your project such that you have some root dir which is your project's main directory. Let's call that /Users/you/projects/MyCoolProject
Within that, make a src/main dir which will contain your sources. A source file goes in a directory that matches its package declaration. com.Model1 is a bad package name for three reasons. Convention states not to start them with caps, convention states that they are supposed to represent either your reverse website or failing that, at least the project name, and finally 'model1' is not descriptive. So let's go with package com.mycompany.coolproject.vehicleModel; instead. In that case, your Model class should be on your disk at /Users/you/projects/MyCoolProject/src/main/com/mycompany/coolproject/vehicleModel/Model.java
Use a build tool such as maven or gradle to build your project. This is going to be a lot simpler than trying to manually make javac do the right thing here. If you MUST use java, make dir build in /users/you/projects/MyCoolProject, make sure you're in that directory, and then try: javac -d build -sourcepath src/main src/main/com/mycompany/coolproject/vehicleModel/*.java and note that you'll have to add a path to that every time you make another package (to avoid having to do that... use maven or gradle).
Once you've done that, this error goes away (the error indicates that javac can't find the other source file because your project isn't properly set up yet. The above instructions lead to a properly set up project, with javac/maven/gradle being capable of finding all your source files as needed, and it's how almost all java programmers work).

Java imported .jar file but jar's class objects cannot resolved

I am trying to send data via usb with Java.And I decided to use the jSerialComm library. I downloaded the required jar file and imported it correctly.
The whole code :
import com.fazecast.jSerialComm.SerialPort;
public class Try{
public static void main(String[] args) throws IOException {
SerialComm ports[] = SerialComm.getCommPorts();
}
}
There is no problem with this row :
import com.fazecast.jSerialComm.SerialPort;
But there is a problem here :
SerialComm ports[] = SerialComm.getCommPorts();
Error message : SerialComm cannot be resolved to a type.
And this is advice : Create class 'SerialComm'
You
import com.fazecast.jSerialComm.SerialPort
But not
import com.fazecast.jSerialComm.SerialComm
SearialPort class is different than SerialComm, you need to import SerialComm class as well.
If you couldn't find it, it means your jar file is not compatible with your snippet code.
you should import this way :
import com.fazecast.jSerialComm.SerialComm
you could check out this if you want to more information :instalation
look at this is a example of send data via usb with Java
check out this :jSerialComm/package-summary

Java- Print the source code of imported class

Is there any way to view the source code of the imported class?
For example
import java.io.Reader;
public class Helper {
public static void main(String args[]){
// print source code of java.io.Reader
}
}
How can I print the source code of java.io.Reader in my class?
Why do you want to print the source code of imported class.
Yes you can view the source code of imported class. In your case source code for Reader can be found in C:\Program Files\Java\jdk1.8.0_101\src.zip\java\io\Reader.java or the path where JDK is installed in your system.
Any .class file can be de-compiled to generate the source code but that will not guarantee to the exact source code.

IntelliJ - AutoCompletion not working for new package

I am testing a few Java API, I've created my project called 'MyLearning' where all my src files are located, in src I created another Package callede 'myfiles', now when I import the java.nio.file.Files API, IntelliJ doesn't show me suggestions for this class. But in the main package i.e src folder, the suggestion works totally fine.
Example:
The above picture shows my main src folder, where the Files API works totally fine.
But then in the new Package that I've created i.e myfiles, it is showing error on retrieving the methods of Files API. Error is
Cannot resolve symbol 'exists'
Can anyone tell me what could be the poblem here?
You have to put method calls inside a method.
public void foo()
{
Files.exists(path);
}
I also noticed that one of the tags you put is intellij-14. The latest version of IntelliJ is 2016.2.
You have to call it in a method, not in the class
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Main {
public static void main(String[] args) {
System.out.println("Hello World!");
Path path = Paths.get("C:\\log.txt");
System.out.println(Files.exists(path));
}
}

apache common configuration library: corrupted property file

I have got a corrupted property file from customer. The file is modified by application to update version number. The code uses apache commons configuration. When I tested, the library always seems to write files in iso-8859-1 format.
Code is simplified to below. What is the possibility of following code write bad file?
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import java.io.FileWriter;
import java.io.IOException;
public class TestConfig {
public void editVersionInfo() throws ConfigurationException, IOException {
String filename = "C:\\temp\\VersionProperties\\Version.properties";
PropertiesConfiguration config = new PropertiesConfiguration(filename);
config.setProperty("application.version", "2011");
config.save(new FileWriter(filename));
}
public static void main(String[] args) throws IOException, ConfigurationException {
TestConfig tc = new TestConfig();
tc.editVersionInfo();
}
}
Just in case - the bad file looks like below. It does not look like in any encoding. The file originally was normal property file with keys and values all in English(ascii chars).
F????Co?aR??m??E?3#?? =
h\u00BD5j\u00B3\u00E0\u0096\u001D\u0081fe\u00BEo\b\u00A3\u0001\u00FE\u00A4\u00DE\u0000\u00FBi\"\u009C{\u00FC\u00D9\u00E2?c\u00F6\u00FF%B\u00A47\u00195\u001EXv\u0097/\u00D7x\u0099\u000E\u00A2gIX\u0014\u0097]k\u00882\u0003\u0014\u0097\u00BC\u00C3\u00AE\u00B4\u001E\u00B3R\u00E4\u00DE&\u0000\u0016\u009B\"7\u0085'\"\u00DCT*v'\u0092\u0007\u0091A\u00BD\u00ACl6~\u0097\u00C0\u00B1\u00D1\u00EB\u00FF\u00A8\u00F3\u0001'\u00BF\u0006\u001F\u009C\fk\u009F\u00C2\u00D9L^_\u0004J4\u00AF\u00D8\u00DAW\u00C4\u00CDj\u00E3\u0095\u00D1+\u00CE?\u0004>Z]\u00D7\u000B\u0098\u0016\u0095\u00AC\u00F7\u00E7\u009ATF\u0019\f)\u00A3\u00A9\u00DC\u00AD\u00ACtq5\u0085\u008E-\u00A3oH\u0000\u00C2\u0092\u00B5\u00F2\u008AG\u008F&\u00F5\u0017H\u0003!\u0083\u00B4\u008AV=\u00E0\u00EDj\u00F0\u00D0J\u00DB\u00CC\u00F2O\u00CE\u00BE\u00F0*4\u0006y~\u00C3\u00B7\"\u000B\u00E4\u00C0$>\u00F3\u00F2~\u00CE\u0097#\u00BAc\u00EC#\u00B4\u00AD\u009A\u00BAX\fF\u0083]\u00C2\u00D4\u00AB\u00F3\u009DQ\u0092\u00854z\u0097\u00FDG\t\u0095\u00E3}ty\u0082I\u00C3`\u009E
??
Edit: The customer environment is japanese. How ever the application is always run with
-Dfile.encoding=UTF8
I suspect your customer has a different default character encoding to what you have. Check their setting of the property file.encoding (counterintuitively named, I know).
An alternative possibility is that you have two threads writing that property file. I don't know, but I suspect the Apache library won't be thread-safe by default.

Categories

Resources