Unexpected results moving files between folders - java

I am trying to add a very simple feature to a Java program. The feature I want to add simply moves all the files from two folders to a third "archive" folder. The code is simple and I understand it 100% the problem is only one of the folder's contents is being moved. I have went over the code with a fine-tooth comb and tried repasting the directory several times, nothing seems to work. If anyone could help me figure out why my 2nd folder's contents aren't being moved I would REALLY appreciate it.
FYI in order to test this code you need to add a couple folders to "My Documents".
"Pain008Files", "Camt54 Files" and "archive". Also you just need to add some type of text file to the Pain008 and Camt5 folder, it can only have a random letter just something that can be moved.
At runtime the Pain008Files folder correctly has all it's files moved to the archive folder. The Camt54 Files does not. The only problem I can think of is that perhaps the space in the Camt54 Files name is causing a problem but that doesn't make sense so I thought I would hold off on changing it till I get some help. Thanks in advance!
Main Class
package fileHandling;
public class moveTestMain
{
public static void main(String args[]){
GetUser gUser = new GetUser();
gUser.getUser();
MoveFiles mFiles = new MoveFiles();
mFiles.moveCamtFiles();
mFiles.movePainFiles();
}
}
Gets the user-name class
package fileHandling;
public class GetUser
{
public static String currentUser = null;
public void getUser(){
currentUser = System.getProperty("user.name");
}
}
Move the files class
package fileHandling;
import java.io.File;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
public class MoveFiles
{
public static ArrayList<File> pain008Files;
public static ArrayList<File> camt54Files;;
public void movePainFiles(){
File pain008File = new File("C:\\Users\\"+GetUser.currentUser+"\\Documents\\Pain008Files");
pain008Files = new ArrayList<File>(Arrays.asList(pain008File.listFiles()));
System.out.println(pain008Files);
for(int i = 0; i < pain008Files.size(); i++){
System.out.println("Test");
int cutAmount = GetUser.currentUser.length();
String fileName = pain008Files.get(i).toString().substring(33+cutAmount,pain008Files.get(i).toString().length());
System.out.println(fileName);
System.out.println(pain008Files.get(i).toString());
pain008Files.get(i).renameTo(new File("C:\\Users\\"+GetUser.currentUser+"\\Documents\\archive\\"+
"archivedPain_"+fileName));
}
}
public void moveCamtFiles(){
File camt54File = new File("C:\\Users\\"+GetUser.currentUser+"\\Documents\\Camt54 Files");
camt54Files = new ArrayList<File>(Arrays.asList(camt54File.listFiles()));
for(int i = 0; i < camt54Files.size(); i++){
int cutAmount = GetUser.currentUser.length();
String fileName = camt54Files.get(i).toString().substring(32+cutAmount,camt54Files.get(i).toString().length());
camt54Files.get(i).renameTo(new File("C:\\Users\\"+GetUser.currentUser+"\\Documents\\archive\\"+
"archivedCamt_"+fileName));
}
}

SHORT ANSWER:
Your code has some typo errors in routes or somewhere...
LONG ANSWER:
I adapted it to local testing in my computer and works fine.
public void movePainFiles() {
File pain008File = new File("C:\\tmp\\pain");
pain008Files = new ArrayList<File>(Arrays.asList(pain008File.listFiles()));
System.out.println(pain008Files);
for (int i = 0; i < pain008Files.size(); i++) {
System.out.println(pain008Files.get(i).toString());
pain008Files.get(i).renameTo(new File("C:\\tmp\\archive\\" + "archivedPain_" + pain008Files.get(i).getName()));
}
}
public void moveCamtFiles() {
File camt54File = new File("C:\\tmp\\camt");
camt54Files = new ArrayList<File>(Arrays.asList(camt54File.listFiles()));
for (int i = 0; i < camt54Files.size(); i++) {
System.out.println(camt54Files.get(i).toString());
camt54Files.get(i).renameTo(new File("C:\\tmp\\archive\\" + "archivedCamt_" + camt54Files.get(i).getName()));
}
}
OUTPUT:
C:\tmp\camt\xxx.pdf
C:\tmp\camt\yyy.pdf
C:\tmp\camt\zzz.pdf
[C:\tmp\pain\Q37024973.txt, C:\tmp\pain\Q37545784.txt]
C:\tmp\pain\Q37024973.txt
C:\tmp\pain\Q37545784.txt

Related

Java: Why can't I declare the reference-variable in one statement and create the referenced object in another statement of the class?

// That doesn't work:
import java.io.File;
public class Test {
File file1;
file1 = new File("path");
}
//--------------------------------------
// The following works:
import java.io.File;
public class Test {
File file1 = new File("path");
}
I don't understand why the first version is not possible.
I also tried it with an int-value (which is not an object - I think):
//Also doesn't work:
public class Test {
int number;
number = 4;
}
Thank you! I tried it and it works (without implementing a non-default constructor or a method):
import java.io.File;
public class Test {
int number;
{
number = 4;
}
File file1;
{
file1 = new File("path");
}
public static void main(String[] args) {
Test test = new Test();
System.out.print(test.number + " , " + test.file1.getName());
// Output: 4 , path
}
}
It's because you cannot have executable code in the class definition outside a method. So the line
file1 = new File("path");
(which is a statement), is illegal. It never gets executed. The class definition is processed at compile time, but the compiler is not a virtual machine, it doesn't execute your code. Statements are executed at runtime.
You can, as B.M noted, create a static piece of code which is executed when the class is loaded. But, I believe it is equivalent to your second example:
File file1 = new File("path");
(but I admit not to have checked the bytecode for that).
You can do it with a block statement :
public class Test {
File file1 ;
{
file1 = new File("path");
}
}

Reading multiple files in directory and printing specific content

What I am trying to achieve is basically a Java file which looks through a specific directory on the users computer, search all the files in the directory for specific word (in this case an email) and then at the end print them out.
The current script of which I have now, looks for all the files in a certain directory, prints out those file names. As well as that I have also figured out how to have that script search through one file for a specific word and then print it out. The only problem is that although it searches through that one file and gets that word/phrase it has to be given the full directory and file to work. I just want it to have a specific directory and then search all the files in it. I have tried doing this using the directory variable of which I have created to find all files, but it does not work when using that as the directory for the files to search through to find the word(s).
Here underneath is the part of my code which is used for the function I want. The actual function is called in my real script so don't worry about that as it is working. I have also just commented in the script what variable I want to work where.
package aProject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class aScanner {
static String usernameMac = System.getProperty("user.name");
final static File foldersMac = new File("/Users/" + usernameMac + "/Library/Mail/V2"); // this is the right directory I want to look through
public static void listFilesForFolder(final File foldersMac) {
for (final File fileEntry : foldersMac.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
try {
BufferedReader bReaderM = new BufferedReader(new FileReader("/Users/username/Library/Mail/V2/AosIMAP-/INBOX.mbox/longnumber-folder/Data/Messages/1.emlx")); //this is where I would like the foldersMac variable to work in, instead of this full directory
String lineMe;
while((lineMe = bReaderM.readLine()) != null)
{
if(lineMe.contains(".com"))
System.out.println(lineMe);
}
bReaderM.close();
}
catch (IOException e) {
}
} else {
System.out.println(fileEntry.getName());
}
}
}
}
I think this is what you're trying to achieve:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class aScanner {
static String usernameMac = System.getProperty("user.name");
final static File foldersMac = new File("/Users/" + usernameMac + "/Library/Mail/V2");
public static void main(String[] args) throws IOException {
listFilesForFolder(foldersMac);
}
public static void listFilesForFolder(final File foldersMac) throws IOException {
for (final File fileEntry : foldersMac.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
} else {
ArrayList<String> lines = new ArrayList<>();
try (BufferedReader bReaderM = new BufferedReader(new FileReader(fileEntry))) {
String lineMe;
while ((lineMe = bReaderM.readLine()) != null) {
if (lineMe.contains(".com")) {
lines.add(lineMe);
}
}
}
if (!lines.isEmpty()) {
System.out.println(fileEntry.getAbsolutePath() + ":");
for (String line : lines) {
System.out.println(" " + line.trim());
}
}
}
}
}
}
I think your problem lies around your recursion logic,
You go down recursively in the directory structure, you walk through you tree, but write out nothing cause of this if statement:
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
...
}
Close that If statement earlier, then it should work.

Why is this not creating a properties file?

I am trying to make a properties file in Java. Sadly, when I startup Minecraft (As this is a mod in Forge) the file is not created. I will be so thankful to anyone who helps me. Here is the code:
package mymod.properties;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class WriteToProperties {
public static void main(String[] args) {
Properties prop = new Properties();
try {
prop.setProperty("Test", "Yay");
prop.store(new FileOutputStream("Test.properties"), null);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Basically what you want is initialize(event.getSuggestedConfigurationFile());
Forge basically wishes to hand you the default settings to you. I also suggest you structure things logically, so it's nice, clean and accessible later on, and easier to manage.
I use this as a config loader
package tschallacka.magiccookies.init;
import java.io.File;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.common.config.Property;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import tschallacka.magiccookies.MagicCookies;
import tschallacka.magiccookies.api.ModHooks;
import tschallacka.magiccookies.api.Preferences;
public class ConfigLoader {
public static Configuration config;
public static final String CATEGORY_GENERAL = "GeneralSettings";
public static final String CATEGORY_SERVER = "ServerPerformance";
public static void init(FMLPreInitializationEvent event) {
ModHooks.MODID = MagicCookies.MODID;
ModHooks.MODNAME = MagicCookies.MODNAME;
ModHooks.VERSION = MagicCookies.VERSION;
try {
initialize(event.getSuggestedConfigurationFile());
}
catch (Exception e) {
MagicCookies.log.error("MagicCookie failed to load preferences. Reverting to default");
}
finally {
if (config != null) {
save();
}
}
}
private static void initialize(final File file) {
config = new Configuration(file);
config.addCustomCategoryComment(CATEGORY_GENERAL, "General Settings");
config.addCustomCategoryComment(CATEGORY_SERVER, "Server performance settings");
Preferences.magicCookieIsLoaded = true;
config.load();
syncConfigurable();
}
private static void save() {
config.save();
}
private static void syncConfigurable() {
final Property awesomeMod = config.get(Configuration.CATEGORY_GENERAL, "awesome_mod", Preferences.awesomeMod);
awesomeMod.comment = "Set this to yes if you think this mod is awesome, maybe it will at some time unlock a special thing.... or not... but that's only for people who think this is an wesome Mod ;-)";
Preferences.awesomeMod = awesomeMod.getString();
final Property numberOfBlocksPlacingPerTickByStripper = config.get(CATEGORY_SERVER,"number_of_blocks_placing_per_tick_by_stripper",Preferences.numberOfBlocksPlacingPerTickByStripper);
numberOfBlocksPlacingPerTickByStripper.comment = "This affects how many blocks will be placed per tick by the creative stripper tool per tick. The stripper tool will only place blocks if ticks are take less than 50ms. If you experience lag lower this number, if you don't experience lag and want faster copy pasting, make this number higher. For an awesome slowmo build of your caste set this to 1 ;-). Set to 0 to render everything in one go per chunk";
Preferences.numberOfBlocksPlacingPerTickByStripper = numberOfBlocksPlacingPerTickByStripper.getInt();
final Property averageTickTimeCalculationSpan = config.get(CATEGORY_SERVER,"number_of_ticks_used_for_average_time_per_tick_calculation",Preferences.averageTickTimeCalculationSpan);
averageTickTimeCalculationSpan.comment = "This number is the number of tick execution times are added together to calculation an average. The higher number means less lag by some things like the strippers, but can also lead to longer execution times for the strippers. Basically if your server is always running behind on server ticks set this value to 1, to at least get some work done when your server is running under 50ms tickspeed";
Preferences.averageTickTimeCalculationSpan = averageTickTimeCalculationSpan.getInt();
final Property acceptableTickduration = config.get(CATEGORY_SERVER,"acceptable_tick_duration",Preferences.acceptableTickduration);
acceptableTickduration.comment = "Define here what you see as acceptable tick speed where MagicCookies can do some of its magic. If average tick speed or current tick speed is higher than this value it won't perform some tasks to help manage server load.";
Preferences.acceptableTickduration = (long)acceptableTickduration.getDouble();
}
}
The value holder Preferences class.
This is purely so I can do Preferences.valuename everywhere.
package tschallacka.magiccookies.api;
/**
* Here the preferences of MagicCookies will be stored
* and kept after the config's are loaded.
* #author Tschallacka
*
*/
public class Preferences {
public static boolean magicCookieIsLoaded = false;
public static String awesomeMod = "Well?";
public static boolean isLoadedThaumcraft = false;
public static int numberOfBlocksPlacingPerTickByStripper = 0;
public static int averageTickTimeCalculationSpan = 60;
public static long acceptableTickduration = 50l;
public static int darkShrineFrequency = 0;
public static boolean darkShrineSpawnLogging = true;
public static boolean entropyTempleSpawnLogging = true;
public static int entropySize = 30;
}
In your main mod file:
#EventHandler
public void preInit(FMLPreInitializationEvent e) {
MagicCookies.log.warn("Preinit starting");
MinecraftForge.EVENT_BUS.register((Object)MagicCookies.instance);
ConfigLoader.init(e);
}
And after that you can just fetch all your preferences from the Preferences class
This file was created in root of your project. If you want some specific path to save, create folder in root of your project like props and change path in FileOutputStream constructor to "props\\Test.properties"

Running the SimulationStarter class in the AlgoTrader

I am trying to run the SimulationStarted class with the moving average strategy in the open source edition of AlgoTrader.
When I start the SimulationStarter I get ArrayIndexOutOfBoundsException.
I am trying to run it through eclipse. From AlgoTrader they run it with the following command
java.exe -cp target/classes;../../AlgoTrader/code/target/classes;../../AlgoTrader/code/lib/*;target/* -Dsimulation=true -DdataSource.dataSet=1year com.algoTrader.starter.SimulationStarter simulateWithCurrentParams
So is it even possible to run it through eclipse or this is the only way?
If anyone has any ideas or suggestions it will be much appreciated.
Here is the code for the SimulationStarter and ServiceLocator classes.
package com.algoTrader.starter;
import org.apache.commons.math.*;
import org.apache.log4j.Logger;
import com.algoTrader.ServiceLocator;
import com.algoTrader.service.SimulationServiceImpl;
import com.algoTrader.util.MyLogger;
public class SimulationStarter {
private static Logger logger = MyLogger.getLogger(SimulationServiceImpl.class.getName());
public static void main(String[] args) throws ConvergenceException, FunctionEvaluationException {
ServiceLocator.serverInstance().init("beanRefFactorySimulation.xml");
if ("simulateWithCurrentParams".equals(args[0])) {
ServiceLocator.serverInstance().getSimulationService().simulateWithCurrentParams();
} else if ("optimizeSingleParamLinear".equals(args[0])) {
String strategyName = args[1];
for (int i = 2; i < args.length; i++) {
String[] params = args[i].split(":");
String parameter = params[0];
double min = Double.parseDouble(params[1]);
double max = Double.parseDouble(params[2]);
double increment = Double.parseDouble(params[3]);
ServiceLocator.serverInstance().getSimulationService().optimizeSingleParamLinear(strategyName, parameter, min, max, increment);
}
}
ServiceLocator.serverInstance().shutdown();
}
}
And the service locator class
package com.algoTrader;
import com.algoTrader.entity.StrategyImpl;
import com.algoTrader.util.ConfigurationUtil;
public class ServiceLocator {
private static boolean simulation = ConfigurationUtil.getBaseConfig().getBoolean("simulation");
private static String strategyName = ConfigurationUtil.getBaseConfig().getString("strategyName");
public static CommonServiceLocator commonInstance() {
if (!simulation && !StrategyImpl.BASE.equals(strategyName)) {
return RemoteServiceLocator.instance();
} else {
return ServerServiceLocator.instance();
}
}
public static ServerServiceLocator serverInstance() {
if (!simulation && !StrategyImpl.BASE.equals(strategyName)) {
throw new IllegalArgumentException("serverInstance cannot be called from the client");
} else {
return ServerServiceLocator.instance();
}
}
}
To Fix this error you will need to open the Run Configuraitons in Eclipse and Add the program Arguments and the VM Arguments and the ArrayIndexOutOfBoundsException will be gone.
The bad news are that there is another error: 2014-01-22 11:15:35,771 ERROR JDBCExceptionReporter Access denied for user 'algouser'#'localhost' (using password: YES)
Which I will be investigating now
In order to run AlgoTrader you need to have a database (MySQL) and configure DB in the source code of AlgoTrader. Without DB AlgoTrader does not work.

jAudio Feature Extractor : Null Exception

My project is to create an Android app that can perform feature extraction and classification of audio files. So first, I'm creating a Java application as a test run.
I'm attempting to use jAudio's feature extractor package to extract audio features from an audio file.
As a starter, I want to input a .wav file and run the feature extraction operation upon that file, and then store the results as an .ARFF file.
However, I'm getting the below NullPointer Exception error from a package within the project:
Exception in thread "main" java.lang.NullPointerException
at java.io.DataOutputStream.writeBytes(Unknown Source)
at jAudioFeatureExtractor.jAudioTools.FeatureProcessor.writeValuesARFFHeader(FeatureProcessor.java:853)
at jAudioFeatureExtractor.jAudioTools.FeatureProcessor.<init>(FeatureProcessor.java:258)
at jAudioFeatureExtractor.DataModel.extract(DataModel.java:308)
at Mfccarffwriter.main(Mfccarffwriter.java:70)
Initially I thought it was a file permission issue(i.e, the program was not being allowed to write a file because of lack of permissions), but even after granting every kind of permission to Eclipse 4.2.2(I'm running Windows 7, 64 bit version), I'm still getting the NullException bug.
The package code where the offending exception originates from is given below:
/**
* Write headers for an ARFF file. If saving for overall features, this must
* be postponed until the overall features have been calculated. If this a
* perWindow arff file, then all the feature headers can be extracted now
* and no hacks are needed.
* <p>
* <b>NOTE</b>: This procedure breaks if a feature to be saved has a
* variable number of dimensions
*
* #throws Exception
*/
private void writeValuesARFFHeader() throws Exception {
String sep = System.getProperty("line.separator");
String feature_value_header = "#relation jAudio" + sep;
values_writer.writeBytes(feature_value_header); // exception here
if (save_features_for_each_window && !save_overall_recording_features) {
for (int i = 0; i < feature_extractors.length; ++i) {
if (features_to_save[i]) {
String name = feature_extractors[i].getFeatureDefinition().name;
int dimension = feature_extractors[i]
.getFeatureDefinition().dimensions;
for (int j = 0; j < dimension; ++j) {
values_writer.writeBytes("#ATTRIBUTE \"" + name + j
+ "\" NUMERIC" + sep);
}
}
}
values_writer.writeBytes(sep);
values_writer.writeBytes("#DATA" + sep);
}
}
Here's the main application code:
import java.io.*;
import java.util.Arrays;
import com.sun.xml.internal.bind.v2.runtime.RuntimeUtil.ToStringAdapter;
import jAudioFeatureExtractor.Cancel;
import jAudioFeatureExtractor.DataModel;
import jAudioFeatureExtractor.Updater;
import jAudioFeatureExtractor.Aggregators.AggregatorContainer;
import jAudioFeatureExtractor.AudioFeatures.FeatureExtractor;
import jAudioFeatureExtractor.AudioFeatures.MFCC;
import jAudioFeatureExtractor.DataTypes.RecordingInfo;
import jAudioFeatureExtractor.jAudioTools.*;
public static void main(String[] args) throws Exception {
// Display information about the wav file
File extractedFiletoTest = new File("./microwave1.wav");
String randomID = Integer.toString((int) Math.random());
String file_path = "E:/Weka-3-6/tmp/microwave1.wav";
AudioSamples sampledExampleFile = new AudioSamples(extractedFiletoTest,randomID,false);
RecordingInfo[] samplefileInfo = new RecordingInfo[5];
samplefileInfo[1] = new RecordingInfo(randomID, file_path, sampledExampleFile, true);
double samplingrate= sampledExampleFile.getSamplingRateAsDouble();
int windowsize= 4096;
boolean normalize = false;
OutputStream valsavepath = new FileOutputStream(".\\values");
OutputStream defsavepath = new FileOutputStream(".\\definitions");
boolean[] featurestosaveamongall = new boolean[10];
Arrays.fill(featurestosaveamongall, Boolean.TRUE);
double windowoverlap = 0.0;
DataModel mfccDM = new DataModel("features.xml",null);
mfccDM.extract(windowsize, 0.5, samplingrate, true, true, false, samplefileInfo, 1); /// invokes the writeValuesARFFHeader function.
}
}
You can download the whole project (done so far)here.
This may be a bit late but I had the same issue and I tracked it down to the featureKey and featureValue never being set in the DataModel. There is not a set method for these but they are public field. Here is my code:
package Sound;
import jAudioFeatureExtractor.ACE.DataTypes.Batch;
import jAudioFeatureExtractor.DataModel;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
public class Analysis {
private static String musicFile = "/home/chris/IdeaProjects/AnotherProj/res/SheMovesInHerOwnWay15s.wav";
private static String featureFile = "/home/chris/IdeaProjects/AnotherProj/res/features.xml";
private static String settingsFile = "/home/chris/IdeaProjects/AnotherProj/res/settings.xml";
private static String FKOuputFile = "/home/chris/IdeaProjects/AnotherProj/res/fk.xml";
private static String FVOuputFile = "/home/chris/IdeaProjects/AnotherProj/res/fv.xml";
public static void main(String[] args){
Batch batch = new Batch(featureFile, null);
try{
batch.setRecordings(new File[]{new File(musicFile)});
batch.getAggregator();
batch.setSettings(settingsFile);
DataModel dm = batch.getDataModel();
OutputStream valsavepath = new FileOutputStream(FVOuputFile);
OutputStream defsavepath = new FileOutputStream(FKOuputFile);
dm.featureKey = defsavepath;
dm.featureValue = valsavepath;
batch.setDataModel(dm);
batch.execute();
}
catch (Exception e){
e.printStackTrace();
}
}
}
I created the settings.xml file using the GUI and just copied the features.xml file from the directory where you saved the jar.
Hope this helps

Categories

Resources