Using a separate java files methods - java

This question is about Android, although i dont think that this is android-specific.
I have a project that i want to use two files with: MainActivity.java and filetools.java . I have three methods in filetools.java, read, write and append.
I want to be able to do something like this in my MainActivity:
filetools.write("/sdcard/file.txt", "something");
The code for MainActivity is just the package, imports, the class, and onCreate.
The code for filetools:
package com.tylerr147.FileRW;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Scanner;
public class filetools
{
public String read(String fName){
try{
File mFile = new File(fName);
String content = new Scanner(mFile).useDelimiter("\\Z").next();
return content;
}catch(Exception e) {
return "There was an error retrieving your file. The proccess returned this error:\n"+e.toString();
}
}
public boolean write(String loc, String stuff) {
File mfile = new File(loc);
try {
mfile.createNewFile();
FileOutputStream f = new FileOutputStream(mfile);
OutputStreamWriter f2 = new OutputStreamWriter(f);
f2.append(stuff);
f2.close();
f.close();
} catch(IOException e) {
return false;
}
return true;
}
public void append(String filename, String content) {
write(filename, read(filename)+content);
}
}
Another thing i would like to be able to do is to have a completely different app by the package com.app.importer
how could i do something like
import com.app.importer;
importerAppsMethod();
I have found a few posts on stackoverflow, but they do not help.
Importing my custom class and calling it's method?
There are a few more, and i have searched and can not find anything that works for me. Any help is appreciated

I am putting #ishmaelMakitla comment intocan answer.
To do something like filetools.write("/sdcard/file.txt", "something"); - you need to declare the write method as static. For example: public static boolean write(String loc, String stuff). You may have to do the same for all other methods if you want similar behavior. Is this what you are looking for?

Related

Generating a new java class by writing java program in another java class [duplicate]

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.

Retrieve code executed by function in Java

I'm trying to analyse some bits of Java-code, looking if the code is written too complexly. I start with a String containing the contents of a Java-class.
From there I want to retrieve, given a function-name, the "inner code" by that function. In this example:
public class testClass{
public int testFunction(char x) throws Exception{
if(x=='a'){
return 1;
}else if(x=='{'){
return 2;
}else{
return 3;
}
}
public int testFunctionTwo(int y){
return y;
}
}
I want to get, when I call String code = getcode("testFunction");, that code contains if(x=='a'){ ... return 3; }. I've made the input code extra ugly, to demonstrate some of the problems one might encounter when doing character-by-character-analysis (because of the else if, the curly brackets will no longer match, because of the Exception thrown, the function declaration is not of the form functionName{ //contents }, etc.)
Is there a solid way to get the contents of testFunction, or should I implement all problems described manually?
You need to a java parser. I worked too with QDox. it is easy to use. example here:
import com.thoughtworks.qdox.JavaProjectBuilder;
import com.thoughtworks.qdox.model.JavaClass;
import com.thoughtworks.qdox.model.JavaMethod;
import java.io.File;
import java.io.IOException;
public class Parser {
public void parseFile() throws IOException {
File file = new File("/path/to/testClass.java");
JavaProjectBuilder builder = new JavaProjectBuilder();
builder.addSource(file);
for (JavaClass javaClass : builder.getClasses()) {
if (javaClass.getName().equals("testClass")) {
for (JavaMethod javaMethod : javaClass.getMethods()) {
if (javaMethod.getName().equals("testMethod")) {
System.out.println(javaMethod.getSourceCode());
}
}
}
}
}
}
Have you considered using a parser to read your code? There are a lot of parsers out there, the last time I worked on a problem like this http://qdox.codehaus.org made short work of these kinds of problems.

how to store java.util.prefs.Preferences in file?

I'm using java.util.prefs.Preferences for application preferences.
And I need ability to edit those preferences manually.
Is it possible to store it into file instead of Windows Registry?
Or I should use another mechanism instead of java.util.prefs.Preferences?
If you want to continue using the Preferences API, but write to a file, you will need a new PreferencesFactory, as detailed in this SO post.
You are going to want to use the following two method :
Preferences.exportSubtree(OutputStream os)
and
Preferences.importPreferences(InputStream is)
This code should help you [http://java.sun.com/developer/technicalArticles/releases/preferences/]:
public class PrefSave {
private static final String PACKAGE = "/pl/test";
public static void main(String[] args) {
doThings(Preferences.systemRoot().node(PACKAGE));
doThings(Preferences.userRoot().node(PACKAGE));
}
public static void doThings(Preferences prefs) {
prefs.putBoolean("Key0", false);
prefs.put("Key1", "Value1");
prefs.putInt("Key2", 2);
Preferences grandparentPrefs = prefs.parent().parent();
grandparentPrefs.putDouble("ParentKey0", Math.E);
grandparentPrefs.putFloat("ParentKey1", (float) Math.PI);
grandparentPrefs.putLong("ParentKey2", Long.MAX_VALUE);
String fileNamePrefix = "System";
if (prefs.isUserNode()) {
fileNamePrefix = "User";
}
try {
OutputStream osTree = new BufferedOutputStream(
new FileOutputStream(fileNamePrefix + "Tree.xml"));
grandparentPrefs.exportSubtree(osTree);
osTree.close();
OutputStream osNode = new BufferedOutputStream(
new FileOutputStream(fileNamePrefix + "Node.xml"));
grandparentPrefs.exportNode(osNode);
osNode.close();
} catch (IOException ioEx) {
// ignore
} catch (BackingStoreException bsEx) {
// ignore too
}
}
Try the following class which allows you to use some simple put() and get() functions using a local configuration.xml file.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.InvalidPropertiesFormatException;
import java.util.Properties;
public class SimpleProperties
{
private String propertiesFilePath;
private Properties properties;
public SimpleProperties() throws InvalidPropertiesFormatException, IOException
{
propertiesFilePath = "configuration.xml";
properties = new Properties();
try
{
properties.loadFromXML(new FileInputStream(propertiesFilePath));
} catch (InvalidPropertiesFormatException e)
{
}
}
public void put(String key, String value) throws FileNotFoundException, IOException
{
properties.setProperty(key, value);
store();
}
public String get(String key)
{
return properties.getProperty(key);
}
private void store() throws FileNotFoundException, IOException
{
String commentText = "Program parameters";
properties.storeToXML(new FileOutputStream(propertiesFilePath), commentText);
}
}
It is explained in another post, here
Properties prop = new Properties();
InputStream in = getClass().getResourceAsStream("foo.properties");
prop.load(in);
in.close()
I think you can use property files instead. They are stored in the file system. You can define the path you want. And you can edit it by hand. See this question for more details.
A while back I had to come up with an implementation of the Preferences class that would read settings from but not write to the registry. I derived a ReadOnlyPreferences class from AbstractPreferences to accomplish this. Later, I needed this exact same functionality you require to go to/from files. I just extended my ReadOnlyPreferences class to override sync() and flush() to keep the file in sync. The cool part about this it would use the exact same logic to apply defaults to the values just like the usual use of the prefs since nothing actually existed in the registry to read. I kept the file in sync by using exportSubtree() and importPreferences() from the base class to do all the heavy lifting for me.
I am sorry I cannot post the code as I don't own it but I used the encrypted preferences stuff you can find at the following link as a start point. That's what I did and it took me about an hour to distill it down to just what I needed which was mainly throwing code away which is much easier than writing code! It is also published in Dr Dobbs at the following link if you don't want to click on the first one. I just never saw an easy place on the dobbs article to download the entire source. Regardless, the article is the best I've seen for extending the preferences stuff.
http://www.panix.com/~mito/articles/#ep
http://www.drdobbs.com/security/encrypted-preferences-in-java/184416587?pgno=4

Java JFileChooser with Filter to supposedly display ONLY directories fail to show just directories

(Thanks in advance! Please let me know if you need more info. Sample code at the bottom.)
Problem I'm trying to solve:
I'm trying to get this JFileChooser object to display only directories (and not files), through the use of a javax.swing.filechooser.FileFilter object that has this in the accept(File file) overridden method: return file.isDirectory();. However, at least on my mac, it doesn't seem to prevent files from being displayed along with the directories (it does prevent files from being selected without using the setFileSelectionMode() method).
Question
Am I missing something? If not, has anyone ever encountered this before?
My understanding/assumptions:
The magic should happen when you pass in a javax.swing.filechooser.FileFilter object into the JFileChooser's setFileFilter() method.
Seems like my JFileChooser with setFileFilter() is behaving like its using of setSelectionMode( JFileChooser.DIRECTORIES_ONLY );
Code
import java.io.File;
import javax.swing.filechooser.FileFilter;
// inside a method that's adding this to a JPanel
_fileChooser = new JFileChooser( "." );
_fileChooser.setControlButtonsAreShown( false );
_fileChooser.setFileFilter( new FolderFilter() );
// _fileChooser.setFileSelectionMode( JFileChooser.DIRECTORIES_ONLY );
_panelMidLeft.add( _fileChooser );
// an inner class, defined somewhere else in the class
private class FolderFilter extends javax.swing.filechooser.FileFilter {
#Override
public boolean accept( File file ) {
return file.isDirectory();
}
#Override
public String getDescription() {
return "We only take directories";
}
}
Thanks!
Alex
Your code works for me. My SSCCE:
import java.io.File;
import javax.swing.JFileChooser;
public class ShowDirectoriesOnly {
public static void main(String[] args) {
JFileChooser fileChooser = new JFileChooser( "." );
fileChooser.setControlButtonsAreShown( false );
fileChooser.setFileFilter( new FolderFilter() );
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fileChooser.showOpenDialog(null);
}
private static class FolderFilter extends javax.swing.filechooser.FileFilter {
#Override
public boolean accept( File file ) {
return file.isDirectory();
}
#Override
public String getDescription() {
return "We only take directories";
}
}
}
If you're still having problems, your best is to create your own SSCCE that demonstrates your problem.
Edit
Screenshot on how it looks under OS X with JDK1.7

Error: Could not find or load main class- Novice

Hi I am a novice in JAVA. I have been getting this file not found exception inspite of the file existing in the very location I have specified in the path which is
Initially I had the issue of file not found. However, after performing a clean and re-run, now I am having an issue which says
Error: Could not find or load main class main.main
import Message.*;
import java.util.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.PrintWriter;
public class main{
public static void main(String[] args) {
Message msg=new Message("bob","alice","request","Data####");
MPasser passerObj=new MPasser("C:\\Workspace\\config.txt","process1");
}
}
Also in the MPasser Constructor the following piece of relevant code is there
public class MPasser(String file_name,String someVariable){
InputStream input;
try {
input =new RandomAccessFile(file_name,"r");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Yaml yaml = new Yaml();
Map<String, String> Object = (Map<String, String>) yaml.load(input);
}
Sorry I have made edits from initial query so that it is more clear
On this line:
input = RandomAccessFile("C:\Workspace\conf.txt",'r');
You need to escape the \'s
input = RandomAccessFile("C:\\Workspace\\conf.txt",'r');
"C:\Workspace\conf.txt"
Those are escape sequences. You probably meant:
"C:\\Workspace\\conf.txt"
You also appear to call it config.txt in one snippet and conf.txt in the other?
Make sure the java process has permissions to read the file.
You have to escape the backslash.
input = RandomAccessFile("C:\\Workspace\\conf.txt",'r');
and also
input = new RandomAccessFile("C:\\Workspace\\conf.txt",'r');
and why you have two different filename conf.txt and config.txt.

Categories