I hava the following class which creates a .txt file
and writes data in this file.
package junitexport;
import java.io.FileWriter;
import java.io.IOException;
import org.junit.runner.JUnitCore;
public class ExecuteWithRunListener {
public static void main(String[] args) throws IOException {
String filename = "report.txt";
FileWriter fw = new FileWriter(filename,true);
fw.write("add a line");
fw.close();
JUnitCore runner = new JUnitCore();
runner.addListener(new ExecutionListener());
runner.run(MyUnitTest.class);
}
}
My question is how can I access the same file from another class.
import org.junit.runner.notification.Failure;
import org.junit.runner.notification.RunListener;
import junitexport.ExecuteWithRunListener;
public class ExecutionListener extends RunListener
{
/*
* Called when an atomic test is about to be started.
*/
public void testStarted(Description dsc) throws java.lang.Exception
{
//I want to write additional data to the previous file here
}
}
BR
As it is a text file, you can use Files.write()
public void testStarted(Description dsc) throws java.lang.Exception
{
Files.write(
Paths.get("report.txt"),
"the text you want to insert".getBytes(),
StandardOpenOption.APPEND
);
}
Use OO principles. Create a class to manage this functionality. Move your code from main into a public method and call this from both places.
Suggest a method to create the file and one to update the existing file
In your Unit Test source file, simple create a new instance of your newly created class and call the methods on this to test it.
Related
I am making a stock market simulator app in java, and there is an issue in the deleteHistoryFiles() method. It says that array is null. However, I have no idea what array this error is talking about.
Here's the code (I've deleted some methods to save space):
package stock.market.simulator;
import java.util.Random;
import java.text.DecimalFormat;
import java.util.Timer;
import java.util.TimerTask;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class StockMarketSimulator {
// Path to where the files are stored for rate history
// USE WHEN RUNNING PROJECT IN NETBEANS
//public static final String HISTORYFILEPATH = "src/stock/market/simulator/history/";
// Path to history files to be used when executing program through jar file
public static final String HISTORYFILEPATH = "history/";
public static void main(String[] args) throws IOException {
accountProfile accProfile = accountCreation();
stockProfile[][] stockProfile = createAllStocks();
deleteHistoryFiles(new File(HISTORYFILEPATH));
createHistoryFiles(stockProfile);
mainWindow window = new mainWindow(accProfile, stockProfile);
recalculationLoop(stockProfile, window);
}
// Procedure to create the history files
public static void createHistoryFiles(stockProfile[][] stocks) throws IOException {
String fileName;
FileWriter fileWriter;
for (stockProfile[] stockArray : stocks) {
for (stockProfile stock : stockArray) {
fileName = stock.getProfileName() + ".csv";
fileWriter = new FileWriter(HISTORYFILEPATH + fileName);
}
}
}
// Procedure to delete the history files
public static void deleteHistoryFiles(File directory) {
for (File file : directory.listFiles()) {
if (!file.isDirectory()) {
file.delete();
}
}
}
}
I got the same exception in exactly the same scenario. I tried to create an array of files by calling File.listFiles() and then iterating the array.
Got exception Cannot read the array length because "<local3>" is null.
Problem is that the path to the directory simply does not exist (my code was copied from another machine with a different folder structure).
I don't understand where is <local1> (sometimes it is <local3>) comes from and what does it mean?
It should be just like this: Cannot read the array length because the array is null.
Edit (answering comment) The sole interesting question in this question is what is a <local1>
My answer answers this question: <local1> is just an array created by File.listFiles() method. And an array is null because of the wrong path.
This question already has answers here:
How do I create a file and write to it?
(35 answers)
Closed 3 years ago.
I want to create a java program that generates another java class in the same project. For example in the class Dragon.java, i want to write java code that creates another java class called fire.java. I do not want to use any GUI from eclipse, just pure code that generates another class from the execution of written programming in java.
I have tried making objects of a non existent class in hopes of the program automatically producing a class with that name.
Again, it doesn't have to be just a java class, is there a way to make other forms of files also? for example fol.flow, or of different names.
Creating a new Java file is easy. You can use any FileWriter technique. But what need to be taken care of is that new Java file is valid java file and can be compiled to class file.
This link has working example of doing the same.
import java.io.*;
import java.util.*;
import java.lang.reflect.*;
public class MakeTodayClass {
Date today = new Date();
String todayMillis = Long.toString(today.getTime());
String todayClass = "z_" + todayMillis;
String todaySource = todayClass + ".java";
public static void main (String args[]){
MakeTodayClass mtc = new MakeTodayClass();
mtc.createIt();
if (mtc.compileIt()) {
System.out.println("Running " + mtc.todayClass + ":\n\n");
mtc.runIt();
}
else
System.out.println(mtc.todaySource + " is bad.");
}
public void createIt() {
try {
FileWriter aWriter = new FileWriter(todaySource, true);
aWriter.write("public class "+ todayClass + "{");
aWriter.write(" public void doit() {");
aWriter.write(" System.out.println(\""+todayMillis+"\");");
aWriter.write(" }}\n");
aWriter.flush();
aWriter.close();
}
catch(Exception e){
e.printStackTrace();
}
}
public boolean compileIt() {
String [] source = { new String(todaySource)};
ByteArrayOutputStream baos= new ByteArrayOutputStream();
new sun.tools.javac.Main(baos,source[0]).compile(source);
// if using JDK >= 1.3 then use
// public static int com.sun.tools.javac.Main.compile(source);
return (baos.toString().indexOf("error")==-1);
}
public void runIt() {
try {
Class params[] = {};
Object paramsObj[] = {};
Class thisClass = Class.forName(todayClass);
Object iClass = thisClass.newInstance();
Method thisMethod = thisClass.getDeclaredMethod("doit", params);
thisMethod.invoke(iClass, paramsObj);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
At first I thought you wanted code generation, but you simply want to write to files or create them?
The simplest code to create file and write to it:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class Testing {
public static void main(String[] args) throws IOException {
Files.writeString(Paths.get("D://output.txt"), "some text to write", StandardOpenOption.CREATE);
}
}
It uses only java standard classes, you don't need any libraries or anything external. Just make sure to write to the valid path, where you have access.
If you want to generate files with java code, you can just do it with the method above, but creating the String with code content is really hard, there are libraries for it and they are not easy to use for beginners. For example javapoet. I personally used javaparser, it has a lot of other possibilities besides generating code.
I am currently dead in the water with a Java programming problem that seemed somewhat simple at first to do! I am trying to write text to a file from MULTIPLE methods in a class that does NOT contain a main() method, unlike other answers of this type question have used.
So... A quick outline of what my program is currently doing:
My program has one class (with the main() method obviously) that reads a text file stored on the disk, and passes sections of the text to certain methods in another class (second file in the project) to simply write the passed text to a text file. Each method in the class without the main() method needs to write the string passed to them to THE SAME file.
Why am I having trouble? I can easily write text to a file from ONE method in the class without the main() with FileWriter, but in order to have all of my other methods to write to the same file, I would need to make FileWriter global. I have tried to make it global, but then when I save text after another method saved text, it just rewrites the file to the latest text written.
My current class without the main() method:
package ADIFTOCSV;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class createADIF {
static File file;
static FileWriter fw;
static BufferedWriter writer;
static void init() throws IOException {
file = new File("/Users/Colin/Desktop/Myadif.txt");
fw = new FileWriter(file.getAbsoluteFile());
writer = new BufferedWriter(fw);
}
static void storeDate(String datez) throws IOException {
writer.write("<QSO_DATE:" + datez.length() + ">" + datez); <<----NULL POINTER EXCEPTION
}
static void storeFreq(String freqz) throws IOException {
writer.write("<FREQ:" + freqz.length() + ">" + freqz);
writer.close();
}
static void storeMode(String modez) {
}
static void storeBand(String bandz) {
}
static void storePower(String pwrz) {
}
static void storeTime(String timez) {
}
static void storeCall(String callz) {
}
static void storeRstSent(String rstsentz) {
}
static void storeRstRcvd(String rstrcvdz) {
}
static void storeComments(String commentsz) {
}
}
Each of these methods needs to write the String passed to them to the SAME file.
storeDate() is the first method to be called, therefore it writes text to the file first. However, when storeFreq() is called, it's text completely replaces the text written by storeDate(). This is obvious because I am forced to create a new FileWriter object in each method in order to write text. I cannot put FileWriter fw = new FileWriter(file.getAbsoluteFile()); outside the method to make it global; errors arise.
Am I missing something? Help is much appreciated. If any questions arise, or clarification is needed, please just ask!
You have to create the writer outside the methods.
Just defining the file outside is not enough.
If you recreate a writer to the same file in each method, of course it will overwrite.
The File instance is just a pointer to the file.
The writer is the "actual handle" that you need to reuse.
And be aware that you have to close the writer if you are finished with writing.
I would suggest that you scrap the class with the static methods and instead create a normal "File Write Handler" class which has a constructor where you can pass the File and writer to intialize the file writing classes and let that class handle all the writing to the file such that you can call a method like this:
FileWriteHandler.writer("<FREQ:" + freqz.length() + ">" + freqz);
and soforth for the rest you want printed. And finally call
FileWriteHandler.close();
Would be much cleaner and you could even make an interface for that class such that you can replace the FileWriterHandler with f.ex. a DatabaseWriteHandler or something like that.
I am working with a Java console application that must write (append) to two separate files, corresponding to OUT and ERR streams. External utilities like tail and grep will be monitoring these files in real-time. I started out writing to these two streams via the Appendable interface, but then it seems like the files don't reflect any changes until the application finishes execution, following a flush and close on the output streams.
Service
package com.mycompany;
public class Service {
private Appendable outlog;
private Appendable errlog;
public Service(Appendable outlog, Appendable errlog) {
this.outlog = outlog;
this.errlog = errlog;
}
public void executeTask() throws Exception {
outlog.append("task execution started\n");
Thread.sleep(30 * 1000);
outlog.append("task execution completed\n");
}
}
Application
package com.mycompany;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.PrintWriter;
public class Application {
public static void main(String[] args) throws Exception {
PrintWriter outlog = new PrintWriter(new BufferedWriter(new FileWriter("application.log")));
PrintWriter errlog = new PrintWriter(new BufferedWriter(new FileWriter("application-err.log")));
Service service = new Service(outlog, errlog);
service.executeTask();
outlog.flush();
outlog.close();
errlog.flush();
errlog.close();
}
}
Is my design fundamentally wrong or should I be doing this in a better and more efficient manner?
In the Service class, declare and propagate the outlog and errlog fields as Writer (which implemets Appendable) and call outlog.flush() after appending you message.
public class Service {
private Writer outlog;
private Writer errlog;
public Service(Writer outlog, Writer errlog) {
this.outlog = outlog;
this.errlog = errlog;
}
public void executeTask() throws Exception {
try {
outlog.append("task execution started\n");
outlog.append("task execution completed\n");
finally {
outlog.flush();
}
}
}
I am writing a java program in eclipse to extract forms from lotusnotes db. Whenever I get a form I need to create a .java file containng a class with same name as of form. Then I have to compile this new .java class which gives me .class file & hence I can create an instance of that new class. I need to know whether this approach of creating,compiling & instantiating a new class is possible from a single existing java program.
My pseudocode goes below
import java.util.Iterator;
import de.bea.domingo.*;
import java.util.List;
import java.io.*;
public class LotusNotesDBExtraction
{
public static void main(String[] args) throws DNotesException,IOException
{
DNotesFactory factory = DNotesFactory.getInstance();
DSession session = factory.getSession();
DDatabase database = session.getDatabase("", "employee.nsf");
List formlist=database.getForms();
//System.out.println("Number of forms are :"+formlist.size());
for(int i=0;i<formlist.size();i++)
{
DForm formn=(DForm)(formlist.get(i));
DForm formname= database.getForm(formn.getName());
**//Creating a class in a file
FileWriter outputfile = new FileWriter("D:\\Lotusnotesformfiles\\"+formn.getName()+".java",true);
BufferedWriter out = new BufferedWriter(outputfile);
out.write("public class "+formn.getName()+" {");
out.newLine();
out.flush();**
try
{
**//Compile the class here**
Process p1 = Runtime.getRuntime().exec("cmd javac \"D:\\Lotusnotesformfiles\\"+formn.getName()+".java\"");
System.out.println("compiled");
}
catch(IOException x)
{
x.printStackTrace();
}
**//instantiate the new class here**
}
}
But I am not able to get .class file for the new class. Can I instantiate the new class in the same program?? I was stuck at this point. Can any please help me
You should be able to do much, if not all, of this using the Reflection API, which allows you to modify classes at runtime, inspect their contents, and even dynamically load classes (for example, after compilation).