I am trying to pass values to variables that probably are not declared yet.
From my main source class I am giving another's class some values, but later on it seems like the values are gone.
Source code:
server.java (main):
public class server {
public static void main(String[] args) {
//Print a simple message to the user to notify there is something going on...
System.out.println("Starting server, please wait...");
//Connecting all class files to the server.
filehandler filehandlerclass = new filehandler();
networking networkingclass = new networking();
//End of class files connecting.
//Preparing the filehandler's file information to open a new filestream.
filehandlerclass.filetohandlename = "server";
filehandlerclass.filetohandleextention = "ini";
filehandlerclass.filetohandlepath = "configs\\";
//Request a new filestream using the filehandler's file variables.
filehandlerclass.openfilestream(filehandlerclass.filestream, filehandlerclass.filetohandle);
//Checks if the filehandler has tried to open a filestream.
if(filehandlerclass.filestreamopen == true) {
//Request a check if the filestream was opened sucessfully.
filehandlerclass.filestreamexists(filehandlerclass.filestream);
}
//If the filehandler has not tried to open a filestream...
else {
System.out.println("Error: The filehandler does not seem to have tried to open a filoestream yet.");
System.out.println("A possibility is that the server could not call the method from the filehandler properly.");
}
//Checks if the boolean "filestreamexists" from the filehandlerclass is true.
if(filehandlerclass.filestreamexists(filehandlerclass.filestream) == true) {
//The filestream seems to exist, let's read the file and extract it's information.
filehandlerclass.readfile(filehandlerclass.filestream);
}
else {
filehandlerclass.openfilestream(filehandlerclass.filestream, filehandlerclass.filetohandle);
}
}
}
filehandler.java:
//Imports the java.io library so the filehandler can read and write to text files.
import java.io.*;
public class filehandler {
//Variables for the filehandler class.
public String filetohandlename;
public String filetohandleextention;
public String filetohandlefullname = filetohandlename + "." + filetohandleextention;
public String filetohandlepath;
public String filetohandle = filetohandlepath + filetohandlefullname;
//Boolean that is true if the filehandler's "openfilestream"-method has tried to open a filestream.
//Is false as long as none filestreams have been touched.
public boolean filestreamopen = false;
//Declares a variable for the filestream to access text files.
public File filestream;
//End of variable list.
//Called to open a filestream so the server can load properties from text files.
public void openfilestream(File filestream, String filetohandle) {
//Tell the user that a filestream is about to be opened.
System.out.println("Opening filestream for \"" + filetohandlefullname + "\"...");
//Open a filestream called "filestream" using the variable "filetohandle"'s value
//as information about wich file to open the filestream for.
filestream = new File(filetohandle);
//Turn the boolean "filestreamopen" to true so next time the server checks it's
//value, it knows if the filehandler has tried to open a filestream.
filestreamopen = true;
}
//Boolean that checks if the filestream exists.
public boolean filestreamexists(File filestream) {
//Tell the user that a check on the filestream is going on.
System.out.println("Checking if filestream for \"" + filetohandlefullname + "\" exists...");
//If the filestream exists...
if(filestream.exists()) {
//Tell the user that the filestream exists.
System.out.println("Filestream for \"" + filetohandlefullname + "\" exists!");
//Make the boolean's value positive.
return true;
}
//If the filestream does not exist...
else {
//Tell the user that the filestream does not exist.
System.out.println("Filestream for \"" + filetohandlefullname + "\" does not exist!");
//Make the boolean's value negative.
return false;
}
}
//Called to read files and collect it's information.
public void readfile(File filestream) {
//Checks if the file that is going to be read is a configuration file.
if(filetohandleextention == "ini") {
//Tell the user that a configuration file is going to be read.
System.out.println("Extracting information from the configuration file \"" + filetohandle + "\".");
}
}
}
networking.java:
public class networking {
}
Problem:
server.java is going to serve commands to the source files and tell them what to do.
The source files are not going to act on their own unless server.java has given them a command.
This way I am planning to be able to write simple function calls in server.java to do greater tasks from the different source files.
server.java seems to pass the variables "filetohandlename", "filetohandleextention" and "filetohandlepath" before the variables are declared and when they get declared, they are declared with "null" as value.
Result:
I get no errors when I compile it.
All I think is happening is a miss match with giving the variables that specifies the file that is going to be read's proper values.
It also throws an exception which I have not been careing to look into for now, either it's because "null.null" does not exist or that I wrote the code wrong.
Final request:
Does anybody know if I can make a method for recieving the variables values
or if there is another more proper way around?
Could I probably make an array of the variables in server.java and collect the values from that array?
Thank you so much for your time.
This:
public String filetohandlename;
public String filetohandleextention;
public String filetohandlefullname = filetohandlename + "." + filetohandleextention;
initialises the first two variables to null, and the third to "null.null". Note that if you change one of the component variables that have made up filetohandlefullname, it won't then change the value of filetohandlefullname. If you want that to happen, then filetohandlefullname should be replaced by a method performing the appending operation.
This:
public void openfilestream(File filestream, String filetohandle)
passes a different variable filetohandle into the method. That variable is distinct from this.filetohandle.
I think there's a numberof issues with this code (above) and I'd do the following.
replace variables instantiated via other variables with methods that perform this dynamically. That way, when you change var1 that you'd expect to change the value of var2, that will happen automatically via a method return. e.g create a private method getFileToHandleFullName() and bin the corresponding variable
scope class members with this
where possible, make those members final so you don't inadvertently change them
This line
public String filetohandlefullname = filetohandlename + "." + filetohandleextention;
is executed when you instantiate the class (ie filehandler filehandlerclass = new filehandler();). At that point in time both variables are unset, thus filetohandlefullname is initialized to null.null
But there's a number of other problems with your code as well, like
//Request a new filestream using the filehandler's file variables.
filehandlerclass.openfilestream(filehandlerclass. filestream,filehandlerclass.filetohandle);
eg you're passing parameters that are fields from the same instance. That's totally useless as the method already has access to those, and it's very confusing.
And maybe slightly controversial:
//Make the boolean's value positive.
return true;
Comments are only useful if they clarify code that without them would be less obvious, and they have to be 100% true and not, as happens so often, what the program wishes the code would do. In this specific case neither of these conditions is fulfilled as the comment doesn't clarify what's going on, and actually the method's return value is set, not some nondescript "boolean's value"
Related
I created a Locale setting so Italian, English, ... I needed to know how to set up a predefined config already: I have obviously tried how every good person does this but I think it is too inefficient, I also tried to create files through the IDE in the same location where the files in the DataFolder are created at the onEnable but obviously it didn't work, however what I tried to be ineffective is this: customConfig.set("Hi-Message", "I'm sorry, i love you");
The way I'm doing it right now, is simply having the config file in the source code itself and, if the file-version of the config does not exist yet, creates a new config file using the config file from the compiled source code.
In my onEnable method in Main, I simply call a method in another class FileManager.setup().
It looks a bit like this in setup():
public static void setup() throws IOException {
File plugin_work_directory = new File(plugin_work_path);
core_server_config = new File(plugin_work_path + "config.txt");
if (!plugin_work_directory.exists()) plugin_work_directory.mkdir();
if (!core_server_config.exists()) {
InputStream core_server_config_template = (Main.class.getResourceAsStream("/config.txt"));
Files.copy(core_server_config_template, Paths.get(plugin_work_path + "config.txt"));
}
Config.load();
if (Integer.parseInt(Config.getValue("config.version")) < Config.version) {
core_server_config.delete();
InputStream core_server_config_template = (Main.class.getResourceAsStream("/config.txt"));
Files.copy(core_server_config_template, Paths.get(plugin_work_path + "config.txt"));
}
Config.load();
}
Config.load() parses the values into a private hashmap of the Config class, whereby other classes can reference the hashmap through a String getValue(String string) method.
public class ScriptCreator {
public static void main(String[] args) throws IOException {
#Choose the CSV file that I am importing the data from
String fName = "C:\\Users\\MyUser\\Downloads\\CurrentApplications (1).csv";
String thisLine;
int count = 0;
FileInputStream fis = new FileInputStream(fName);
DataInputStream myInput = new DataInputStream(fis);
int i = 0;
#Prints the List of names in the CSV file
while((thisLine = myInput.readLine()) != null){
String strar[] = thisLine.split(",");
Printer(strar[0]);
}
}
public static void Printer(String arg) throws IOException{
#Want to pull from the String strar[0] from above
#Says that it cannot be resolved to a variable
String name = arg;
String direc = "C:/Users/MyUser/Documents/";
String path = "C:/Users/MyUser/Documents";
Iterable<String> lines = Arrays.asList("LOGIN -acceptssl ServerName","N " + name + " " + direc ,"cd " + name,"import " + path + "*.ppf" + " true","scan", "publishassessase -aseapplication " + name,"removeassess *","del " + name );
Path file = Paths.get(name + ".txt");
Files.write(file, lines, Charset.forName("UTF-8"));
}
}
Hello everyone and thank you in advance for any help that you may be able to give me. I am trying to create a java program that will pull names from a CSV file and take those names to generate custom outputs for text files. I am having a hard time being able to set a variable that I can use to grab the names that are being printed and using them to generate a text file by setting the name variable.
I am also going to need some help in making sure that it creates the amount of scripts for the amount of names in the CSV file. Ex. 7 names in CSV makes 7 custom .txt files, each with its appropriate name.
Any help is greatly appreciated!
Edit: I have updated my code to match the correction that was needed to make the code work.
It looks like you have some scoping issues. Whenever you declare a variable, it only exists within the boundaries of its closest set of braces. By declaring strar in your main method, the only place you can explicitly use it is within your main method. Your Printer() method doesn't have any previous mention of strar, and the only way it can know about it is by passing it as an argument to the function.
i.e.
Printer(String[] args)
Or, better yet:
Printer(String arg)
and then call it in your while loop with
Printer(strar[0]);
Also, your Printer method begins with a "for each" loop called on strar[0], which is not a valid target for a foreach loop anyway, because if I recall correctly, String isn't an Iterable object. If you implemented the Printer function in the way I recommended, you won't need a for each loop anyway, as there will only be one name passed at a time.
The filesystem AirportHDD is mounted (AFP) from the beginning and the file exists when I start this little program.
I tried to figure out the whole day why the following is not working, but couldnt find any solution:
public static void main(String[] arguments)
{
while(1==1)
{
File f=new File(
"/Volumes/AirportHDD/test/lock.csv");
System.out.println(f.exists());
AmySystem.sleep(100);
}
}
the output is:
true, true, ...
as soon as I remove the file from a different computer (AirportHDD is a mounted harddisk over network) then the output keeps saying:
true, true, ...
when I open the finder and goto this directory the output changes to: false, false, ...
when the file is added again (via another pc) the output is still:
false, false, ...
but if you open the finder again and click on the directory and finder shows the existing file, the output changes suddenly to: false, true, true, true, ...
NOTE:
also all other file operations like opening for read are failing as long as java 'thinks' the file is not there
if the program itself is creating and deleting the files then problem is not occurring
just found out while testing that with samba sharing everything is ok, but with AFP it just wont work
is there a way to tell java to do the same thing as finder, like a refresh, or do not try to cache, whatever?
I think you might be looking for the WatchService. Oracle was also kind enough to provide a tutorial.
Because the longevity of these links aren't guaranteed, I'll edit in an example code in a couple of minutes. I just wanted to let you know I think I found something in case you want to start looking at it for yourself.
UPDATE
Following the linked tutorial, I came up with code like this. I'm not sure it'll work (don't have time to test it), but it might be enough to get you started. The WatchService also has a take() method that will wait for events, which means you could potentially assume the file's existence (or lack thereof) based on the last output you gave. That will really depend on what this program will be interacting with.
If this works, good. If not, maybe we can figure out how to fix it based on whatever errors you're getting. Or maybe someone else will come along and give a better version of this code (or better option altogether) if they're more acquainted with this than I am.
public static void main(String[] arguments) {
Path path = Paths.get("/Volumes/AirportHDD/test/lock.csv");
WatchService watcher = FileSystems.getDefault().newWatchService();
WatchKey key = null;
try {
key = path.register(watcher,
ENTRY_CREATE,
ENTRY_DELETE);
} catch (IOException x) {
System.err.println(x);
}
while(true) {//I tend to favor this infinite loop, but that's just preference.
key = watcher.poll();
if(key != null) {
for (WatchEvent<?> event: key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
if (kind == OVERFLOW || kind == ENTRY_DELETE) {
System.out.println(false);
}
else if (kind == ENTRY_CREATE) {
System.out.println(true);
}
}//for(all events)
}//if(file event occured)
else {
File f=new File(path);
System.out.println(f.exists());
}//else(no file event occured)
AmySystem.sleep(100);
}//while(true)
}//main() method
Here is a JUnit test that shows the problem
The problem still happens using Samba on OSX Mavericks. A possible reason
is explaned by the statement in:
http://appleinsider.com/articles/13/06/11/apple-shifts-from-afp-file-sharing-to-smb2-in-os-x-109-mavericks
It aggressively caches file and folder properties and uses opportunistic locking to enable better caching of data.
Please find below a checkFile that will actually attempt to read a few bytes and forcing a true file access to avoid the caching misbehaviour ...
JUnit test:
/**
* test file exists function on Network drive
* #throws Exception
*/
#Test
public void testFileExistsOnNetworkDrive() throws Exception {
String testFileName="/Volumes/bitplan/tmp/testFileExists.txt";
File testFile=new File(testFileName);
testFile.delete();
for (int i=0;i<10;i++) {
Thread.sleep(50);
System.out.println(""+i+":"+OCRJob.checkExists(testFile));
switch (i) {
case 3:
// FileUtils.writeStringToFile(testFile, "here we go");
Runtime.getRuntime().exec("/usr/bin/ssh phobos /usr/bin/touch "+testFileName);
break;
}
}
}
checkExists source code:
/**
* check if the given file exists
* #param f
* #return true if file exists
*/
public static boolean checkExists(File f) {
try {
byte[] buffer = new byte[4];
InputStream is = new FileInputStream(f);
if (is.read(buffer) != buffer.length) {
// do something
}
is.close();
return true;
} catch (java.io.IOException fnfe) {
}
return false;
}
The problem is the network file system AFP. With the use of SAMBA everything works like expected.
Maybe the OS returns the wrong file info in OSX with the use of AFP in these scenarios.
I am attempting to do what I would have guessed would be pretty simple, but as it turns out is not. I have an ACR122 NFC reader and a bunch of Mifare Classic and Mifare Ultralight tags, and all I want to do is read and write a mime-type and a short text string to each card from a Java application. Here's what I've got working so far:
I can connect to my reader and listen for tags
I can detect which type of tag is on the reader
On the Mifare Classic tags I can loop through all of the data on the tag (after programming the tag from my phone) and build an ascii string, but most of the data is "junk" data
I can determine whether or not there is an Application directory on the tag.
Here's my code for doing that:
Main:
public static void main(String[] args){
TerminalFactory factory = TerminalFactory.getDefault();
List<CardTerminal> terminals;
try{
TerminalHandler handler = new TerminalHandler();
terminals = factory.terminals().list();
CardTerminal cardTerminal = terminals.get(0);
AcsTerminal terminal = new AcsTerminal();
terminal.setCardTerminal(cardTerminal);
handler.addTerminal(terminal);
NfcAdapter adapter = new NfcAdapter(handler.getAvailableTerminal(), TerminalMode.INITIATOR);
adapter.registerTagListener(new CustomNDEFListener());
adapter.startListening();
System.in.read();
adapter.stopListening();
}
catch(IOException e){
}
catch(CardException e){
System.out.println("CardException: " + e.getMessage());
}
}
CustomNDEFListener:
public class CustomNDEFListener extends AbstractCardTool
{
#Override
public void doWithReaderWriter(MfClassicReaderWriter readerWriter)
throws IOException{
NdefMessageDecoder decoder = NdefContext.getNdefMessageDecoder();
MadKeyConfig config = MfConstants.NDEF_KEY_CONFIG;
if(readerWriter.hasApplicationDirectory()){
System.out.println("Application Directory Found!");
ApplicationDirectory directory = readerWriter.getApplicationDirectory();
}
else{
System.out.println("No Application Directory Found, creating one.");
readerWriter.createApplicationDirectory(config);
}
}
}
From here, I seem to be at a loss as for how to actually create and interact with an application. Once I can create the application and write Record objects to it, I should be able to write the data I need using the TextMimeRecord type, I just don't know how to get there. Any thoughts?
::Addendum::
Apparently there is no nfc-tools tag, and there probably should be. Would someone with enough rep be kind enough to create one and retag my question to include it?
::Second Addendum::
Also, I am willing to ditch NFC-Tools if someone can point me in the direction of a library that works for what I need, is well documented, and will run in a Windows environment.
Did you checked this library ? It is well written, how ever has poor documentation. Actually no more than JavaDoc.
I have a problem about creating a textfile with the name I want.
I want to create a textfile named : 'username' Subjects.
private void saveSubjects(){
RegisterFrame r = new RegisterFrame();
String username = r.txtUser.getText();;
try{
FileWriter f = new FileWriter(username + "" + "Subjects" + ".txt", true);
String subjects[] = lstSubjects.getItems();
for(int i = 0; i<subjects.length; i++){
f.write(subjects[i] + "\r\n");
}
f.close();
JOptionPane.showMessageDialog(null, "Data saved!", "Data Saved", JOptionPane.INFORMATION_MESSAGE);
}catch(Exception e){
JOptionPane.showMessageDialog(null, "Nothing Inputted!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
I want to get the username from RegisterFrame as it is inputted there but it's not working.
I know it's a simple thing but I'm still a beginner in this. How can I solve this?
Thanks in advance
try this:
String username = r.txtUser.getText();
System.out.println("The loaded username is: " + username);
then you will see where your problem is : writing into the file OR getting the username text.
If the problem is in getting the text, consider other way of getting it or modify the question by removing the file write part and specifiing the username getting part.
Otherwise, IDK where the error is.
BTW: how is it not working? the file is not created at all? do you see any errors? the file has wrong name? please specify
Your code for writing the file seems to be fine. Based on your code I tried this which worked perfectly:
public static void main(String[] args) {
FileWriter f = null;
try {
f = new FileWriter("Subjects.txt", true);
String subjects[] = {"subject1", "subject2"};
for (String subject : subjects) {
f.write(subject + "\r\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(f);
}
}
I'd say your problem is elsewhere.
Please note that best practice dictates that Closeable objects such as FileWriter should be closed in a finally block
Assuming new RegisterFrame() starts up a GUI window, the issue is your code runs before you have a chance to type in your name. Instead you need to use event listeners to capture the contents of text fields, otherwise the code to get the name runs immediately after the window opens, long before you have a chance to type anything in.
The timeline is like this:
RegisterFrame starts a new thread to display the GUI without blocking your code
Your code immediately pulls "" from txtUser, which is of course empty
Now you type your name in
Nothing happens, because nothing in your code is paying attention to that action
Instead, it should be:
RegisterFrame starts a new thread to display the GUI without blocking your code
The method returns, or starts doing work that isn't dependent on the GUI
Now you type your name in
An event listener is triggered from the new thread, and the associated action to get the name and write to a file is executed
You have to decide what sort of listener makes sense for your use case, for instance you might want to wait until the user clicks a button (that says "Submit" or "Write File" for instance) and register an ActionListener on that button. Then you put your username polling and file writing behavior in that action* and you're golden!
*I should add that in truth you want to do as little as possible in ActionListeners, and it would be better to check if the username is not empty, then pass the actual work off to another thread, for instance with a SwingWorker, but for your purposes I suspect it will be alright to not worry about that.