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.
Related
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 have a static file server at "localhost:8888/fileserver".
I am trying to write a program in java to download the files from the server. The file server consists of three folders, therefore I am trying to write a script that automatically goes through the directory and copies it to my computer.
I know there is a wget function for linux that accomplishes this recursively. Is there a way to do this in Java?
Please could you advise on how I should go about doing this or proceed.
Thank you
Below is a code to go through an online directory and return back all the links needed to download.
After that I just need to download each individual link.
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class WebCrawler {
//Created a global list variable to save the links
static List<String> createList = new ArrayList<String>();
public static void main(String[] args) throws IOException {
String url = "http://localhost:8888";
System.out.println(myCrawler(url)+"\n"+"Size: "+myCrawler(url).size());
}
public static List<String> myCrawler(String url) throws IOException{
//Creates an open connection to a link
Document doc = Jsoup.connect(url).ignoreContentType(true).get();
Elements links = doc.select("a[href]");
//Recursively iterates through all the links provided on the initial url
for (Element i : links) {
String link = print("%s", i.attr("abs:href"));
if (link.endsWith("/")){myCrawler(link);} //Recursive part, calls back on itself
else {createList.add(link);}
}
return createList;
}
//Translates the link into a readable string object
private static String print(String msg, Object... args){return String.format(msg, args);}
}
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.
I have a Sons class which load and play sounds. And an adhd class which contain the main and uses this Sons class.
All my classes are in the package "adhd" and my sounds in the jar, are like this : 1.wav is in SoundN which is in the jar. (ADHD.jar/SoundN/1.wav).
When I run the code in Eclipse it works, but when I run the jar it doesn't. It is important for me to keep the sounds "loading" because I need my program to read my sounds quickly, as I am using timers. What do you suggest me to do?
Here is the code of my class Sons which load sounds in instances of singletons.
Sons
package adhd;
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.FloatControl;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;
import java.applet.Applet;
import java.applet.AudioClip;
import java.net.URL;
public class Sons {
private static String PATH=null;
private static Sons instance;
private final Map<String, Clip> sons;
private boolean desactive;
Sons(String path) {
PATH = path;
sons = new HashMap<String, Clip>();
}
public void load(String nom) throws UnsupportedAudioFileException, IOException, LineUnavailableException {
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(getClass().getResourceAsStream(PATH + nom)));
sons.put(nom, clip);
}
public void play(String son) {
if(!desactive) try {
Clip c = getSon(son);
c.setFramePosition(0);
c.start();
} catch(Exception e) {
System.err.println("Impossible to play the sound " + sound);
desactive = true;
}
}
}
Here is the adhd class which contain the main that uses sounds
Main class : adhd
public static void main(String[] args) {
Sons sonN= new Sons("/SoundN/");
try {
sonN.load("1.wav");
} catch (UnsupportedAudioFileException | IOException
| LineUnavailableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sonN.play("1.wav");
}
Here is also a picture of the tree
Now, thanks to the exception message, we know what the problem actually is. The problem is not that the sounds can't be loaded or aren't found in the jar. The problem is that, as the javadoc says:
These parsers must be able to mark the stream, read enough data to determine whether they support the stream, and, if not, reset the stream's read pointer to its original position. If the input stream does not support these operation, this method may fail with an IOException.
And the stream returned by Class.getResourceAsStream(), when the resource is loaded from a jar, doesn't support these operations. So what you could do is to read everything from the input stream into a byte array in memory, create a ByteArrayInputStream from this byte array, and pass that stream to AudioSystem.getAudioInputStream().
If loading everything in memory is not an option because the sound is really long (but then I guess you wouldn't put it in the jar), then you could write it to a temporary file, and then pass a FileInputStream to AudioSystem.getAudioInputStream().
I am using eclipse and I have my text file in the correct directory (src folder). I just want to read the file and count all the words in it. For some reason I am getting a file not found exception being thrown.
here is my code.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Tester {
public static int getSizeOfDictionary(File dictionary)
throws FileNotFoundException {
int count = 0;
Scanner reader = new Scanner(dictionary);
while (reader.hasNextLine()) {
reader.nextLine();
count++;
}
reader.close();
return count;
}
public static void main(String[] args) throws FileNotFoundException {
File test = new File("words.txt");
System.out.println(getSizeOfDictionary(test));
}
}
You could use this.getClass().getResource("words.txt") which will find that file on the current classpath.
From the main method you could use: Tester.class.getResource("words.txt")
when eclipse launches jvm it sets current directory to project base directory generally (unless you modify the default current directory)
${workspace_loc}/project_name
so you need to change your File initialization to
File test = new File("src/words.txt");
Note:
It will just be limited to this project structure, if you export it to jar it will not work any more, I assume you just need it as part of exercise
You have to use property class to access your file within class-path and source folder
you can try like:
this.getClass().getResourceAsFile("words.txt")