is this the right way to create a java file (Programmatically)? - java

Below is the code to create a java file programmatically
is this the right way? or is there any other way
public static void main(String[] args) throws IOException {
File atlas = new File("D:/WIP/pac/n/sample.txt");
if (!atlas.exists()) {
System.out.println("File not exist");
}
FileHandle mAtlasHandle = new FileHandle(atlas);
BufferedReader reader = mAtlasHandle.reader(1024);
String line = null;
ArrayList<String> mArrayList = new ArrayList<String>();
while ((line = reader.readLine()) != null) {
mArrayList.add(line);
}
File file = new File("D:/WIP/pac/n/Sample.java");
if (!file.exists()) {
file.createNewFile();
}
String packageName = "package com.atom.lib;";
PrintWriter writer = new PrintWriter(file);
String mString = new String(file.getName());
String name = mString.replaceFirst("[.][^.]+$", "");
String output = Character.toUpperCase(name.charAt(0)) + name.substring(1);
writer.println(packageName);
writer.println("public class " + output);
writer.println("{");
for (String obj : mArrayList) {
writer.println("public String " + obj + "=\"" + obj + "\";");
}
writer.println("}");
writer.close();
}

Yes, there is better way. Use CodeModel to create Java files programmatically, instead of using println() or String appending methods. From their website:
CodeModel is a Java library for code generators; it provides a way to generate Java programs in a way much nicer than PrintStream.println(). This project is a spin-off from the JAXB RI for its schema compiler to generate Java source files.
But the main problem with CodelModel is very less documentation. API docs is the only bible you can have for this.
If you are comfortable with Eclipse plugin development, you can use Eclipse's AST to create Java file programmatically. It can even work standalone without having Eclipse.

I have used FreeMarker templates to generate java source file. This is very powerful tool which allows you define a source template and and model where you can define variables, methods and every thing and allow you to compile to to any multiple format(txt, java,etc)
You can start by defining template with placeholder for your required java source,file and then later you can programatically apply the values for placeholder.
Given example illustrate the working of this API, you can extend the example to create java source file
http://viralpatel.net/blogs/freemaker-template-hello-world-tutorial/

Related

How can i write to a file when distributable file is launched?

I have program that read from a file. Now I created another task, that aims to update/write this file into same files. My problem now is when I generate my project's distributable file, during running and try to update my file, it does not write/update my changes. If I run it directly on my IDE, it works fine. This is wha I did so far:
private void tbleAddressMouseClicked(java.awt.event.MouseEvent evt) {
if(tbleAddress.getSelectedColumn()==3){
AddressUtil util = new AddressUtil();
List<AddressUtil> lists = util.getAddresses();
Address address = lists.get(tbleAddress.getSelectedRow());
if(tbleAddress.getValueAt(tbleAddress.getSelectedRow(), 0)!=null){
address.setRegion("\""+tbleAddress.getValueAt(tbleAddress.getSelectedRow(), 0).toString()+"\"");
}
lists.set(tbleAddress.getSelectedRow(), address);
try {
FileWriter fw;
fw = new FileWriter("./src/address.csv"); // This is where I doubt, if my **jar** file reads this directory
for(Address a:lists){
fw.append(a.getRegion);
fw.append(",");
fw.append(a.getAddressName());
fw.append("\n");
fw.flush();
}
fw.close();
} ...
My getAddresses is defined as:
public List<Address> getAddresses() {
List<Address> addresses = new ArrayList<>();
BufferedReader br = null;
InputStream in = this.getClass().getResourceAsStream("/address.csv");
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while((line = reader.readLine())!=null){
String[] result = line.split(",");
Address address = new Address();
address.setRegion(result[0]);
address.setAddressName(result[1]);
addresses.add(address);
}...
My address.csv is of form:
"Region I","Sample St., Sample Address"
"Region II","Sample St., Sample Address 2"
...
Any help is much appreciated
Your issue with writing to the file is most likely due to the relative path you're using when you define the FileWriter. The dot in your path means "current working directory" so if your program is located at path C:\myProgram and you run your program such that it uses this path as the working directory then it's going to look for C:\myProgram\src\address.csv
So depending on the requirements for your program a relative path might be appropriate, in which case you need to determine what the correct path will be and ensure the file exists at that location, or you may to use some other mechanism to find the file.
I also notice that you're using getResourceAsStream to get an InputStream to your file. You should know that this only works if the file is available on the classpath of your program.

FileNotFoundException java cannot basic find file while it's there

I'm trying to read a basic txt file that contains prices in euros. My program is supposed to loop through these prices and then create a new file with the other prices. Now, the problem is that java says it cannot find the first file.
It is in the exact same package like this:
Java already fails at the following code:
FileReader fr = new FileReader("prices_usd.txt");
Whole code :
import java.io.*;
public class DollarToEur {
public static void main(String[] arg) throws IOException, FileNotFoundException {
FileReader fr = new FileReader("prices_usd.txt");
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter("prices_eur");
PrintWriter pw = new PrintWriter(fw);
String regel = br.readLine();
while(regel != null) {
String[] values = regel.split(" : ");
String beschrijving = values[0];
String prijsString = values[1];
double prijs = Double.parseDouble(prijsString);
double newPrijs = prijs * 0.913;
pw.println(beschrijving + " : " + newPrijs);
regel = br.readLine();
}
pw.close();
br.close();
}
}
Your file looks to be named "prices_usd" and your code is looking for "prices_usd.txt"
There are a couple of things you need to do:
Put the file directly under the project folder in Eclipse. When your execute your code in Eclipse, the project folder is considered to be the working directory. So you need to put the file there so that Java can find it.
Rename the file correctly with the .txt extn. From your screen print it looks like the file does not have an extension or may be it's just not visible.
Hope this helps!
It is bad practice to put resource files (like prices_usd.txt) in a package. Please put it under the resources/ directory. If you put it directly in the resources/ directory, you can access the file like this:
new FileReader(new File(this.getClass().getClassLoader().getResource("prices_usd.txt").getFile()));
But if you really have a good reason to put it in the package, you can access it like this:
new FileReader("src/main/java/week5/practicum13/prices_usd.txt");
But this will not work when you export your project (for example: as a jar).
EDIT 0: Also of course, your file's name needs to be "prices_usd.txt" and not just "prices_usd".
EDIT 1: The first (recommended) solution does return a string on .getFile() which can not directly be passed to the new File(...) constructor when the application is built / not run in the IDE. Spring has a solution to it though: org.springframework.core.io.ClassPathResource.
Simply use this code with Spring:
new FileReader(new ClassPathResource("prices_usd.txt").getFile());

How to read from a text file in java when its not saved in the same place

Im trying to write a function that will take a string, then open a file with that string name and read the text. I know how to do this, but im having trouble with the fact that my text files are not saved in the same place as my java file.
It looks like this.
Project name/src/program.java
Project name/resources/text.txt
Im using the File class, but dont know what to put in the File constructor to open to the right place.
ie. File store = new File(xxxxxxxxxtext.txt)
Help me out with what goes in front of the file name please. Also, this is java 6 and im on windows 8.
This is my code:
public static void areaSearch(String a) {
Scanner reader = null;
try {
reader = new Scanner(new File("../resources/" + a+ ".txt"));
}
catch (Exception e) {
System.out.println("File: " + a +" not opended...");
}
Use relative path if it's on an easy relative path from your project folder:
File file = File("../resources/text.txt");
Or use absolute path:
File file = File("C:\\abcfolder\\text.txt");
Read documentation. There are more, than 1 constructor for File class. Use:
public File(File parent, String child)

how to locate a file?

Hi I want to know how the program can locate a file.
For example. I have a class
public class MiReader {
private File file;
private BufferedReader bufferedReader;
public MiReader(String dir) {
try {
file= new File(dir);
bufferedReader = new BufferedReader(new FileReader(file));
} catch (Exception ex) {
Logger.getLogger(MiReader.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void imprimir() {
***
}
}
I know that the file is on the project (I'm using netbeans)
project is on C:\NetBeansProjects\Application
file: C:\NetBeansProjects\Application\file.txt
so when I instance MiReader must be something like this:
MiReader mr = new MiReader("C:\\NetBeansProjects\\Application\\file.txt");
and now if I run the program from another location
for example now its on
D:\Pograms\Application
so the file is D:\Pograms\Application\file.txt
and now I have to change the way I create the class to
MiReader mr = new MiReader("D:\\Pograms\\Application\\file.txt");
I want to know how the program can locate the file just running the program,
something like
MiReader mr = new MiReader(program.getLocation()+"\\file.txt")
Learning english :)
You could use relative paths. Aka
MiReader Mr = new MiReader("file.text");
This way the program will look for the file file.text inside the directory you run it from.
You can use System.getProperty to get the user.home, the user.dir, the classpath etc as a standard prefix for the file you are trying to open. Here are all of the System properties
ie
File f = new File (System.getProperty("user.home" + "/foo.txt"));

Text input and output java

I am trying to read 2 files after i read the files i want to get their contents and manipulate the contents of the two files then update a new file which is the output. The files are in the same folder as the program but the program always throws a FileNotFoundException.
Below is my code:-
import java.io.*;
import java.util.Scanner;
public class UpdateMaster {
public static void main(String[] args)
{
String master = "Customer.dat";
String trans = "Transactns.dat";
String newMaster = "Temp.txt";
Scanner inputStreamMaster = null;
Scanner inputStreamTrans = null;
PrintWriter inputStreamNewMaster = null;
try
{
inputStreamMaster = new Scanner(new File(master));
inputStreamTrans = new Scanner(new File(trans));
inputStreamNewMaster = new PrintWriter(newMaster);
}
catch(FileNotFoundException e)
{
System.out.println("Error: you opend a file that does not exist.");
System.exit(0);
}
catch(IOException e)
{
System.out.println("Error.");
System.exit(0);
}
do
{
String transLine = inputStreamTrans.nextLine();
String masterLine = inputStreamMaster.nextLine();
String[] transLineArr = transLine.split(",");
String[] masterLineArr = masterLine.split(",");
int trAccNo = Integer.parseInt(transLineArr[0]);
int sales = Integer.parseInt(transLineArr[1]);
int masterAccNo = Integer.parseInt(masterLineArr[0]);
int balance = Integer.parseInt(masterLineArr[1]);
while(masterAccNo== trAccNo){
inputStreamNewMaster.println(trAccNo+ " , "+masterAccNo);
masterLine = inputStreamMaster.nextLine();
masterLineArr = masterLine.split(",");
masterAccNo = Integer.parseInt(masterLineArr[0]);
balance = Integer.parseInt(masterLineArr[1]);
}
balance = balance + sales;
inputStreamNewMaster.println(masterAccNo+ " , "+balance);
}while(inputStreamTrans.hasNextLine());
inputStreamMaster.close();
inputStreamTrans.close();
inputStreamNewMaster.close();
//System.out.println(" the line were written to "+ newMaster);
}
}
Like #Ankit Rustagi said in the comments, you need the full path of the files if you want to keep the current implementation.
However, there is a solution where you only need the file names: use BufferedReader / BufferedWriter. See here an example on how to use these classes (in the example it uses the full path but it works without it too).
Use absolute path
String master = "C:/Data/Customer.dat";
String trans = "C:/Data/Transactns.dat";
String newMaster = "C:/Data/Temp.txt";
The code works for me, i guess you misspelled some filename(s) or your files are in the wrong folder. I created your files on the same level as the src or the project. Also this is the folder where the files are exspected.
There's nothing wrong with using relative paths like tihis. What's happening is that your program is looking for the files in the directory where you execute the program, which doesn't have to be the folder of the program. You can confirm this by logging the absolute path of the files before you try to read them. For example:
File masterFile = new File(master);
System.out.printf("Using master file '%s'%n", masterFile.getAbsolutePath());
inputStreamMaster = new Scanner(masterFile);
In general you should not hardcode file paths but allow the user to specify them in someway, for example using command line arguments, a configuration file with a well known path, or an interactive user interface.
There is a way to locate the program's class file but it's a little tricky because Java allows classes to be loaded from compressed archives that may be located in remote systems. It's better to solve this problem in some other manner.
Try this:
String current = new java.io.File( "." ).getCanonicalPath();
System.out.println("I look for files in:"+current);
To see what directory your program expects to find its input files. If it shows the correct directory, check spelling of filenames. Otherwise, you have a clue as to what's gone wrong.

Categories

Resources