How do I write a code template for eclipse? - java

I have some specific code that I need, to be able to have certain I/O stuff that I don't want to write every time, and I just want to be able to add a java class so that it already has that code in there, I tried doing :
/*
ID: my_id
PROG: ${filename}
LANG: JAVA
*/
import java.util.*;
import java.io.*;
import java.net.InetAddress;
public class ${filename} {
static class InputReader {
private StringTokenizer st = null;
private BufferedReader br = null;
public InputReader(String fileName) throws Exception {
try {
br = new BufferedReader(new FileReader(fileName));
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
public InputReader(InputStream in) {
try {
br = new BufferedReader(new InputStreamReader(in), 32768);
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
public static void main(String[] args) throws Exception {
InetAddress addr = InetAddress.getLocalHost();
String hostname = addr.getHostName();
boolean isLocal = hostname.equals("paulpc");
String location = null;
InputReader in = null;
PrintWriter out = null;
if (!isLocal) {
location = ${filename}.class.getProtectionDomain().getCodeSource().getLocation().getPath();
in = new InputReader(location + "/" + "${filename}.in");
out = new PrintWriter(new FileWriter(location + "/" + "${filename}.out"));
} else {
in = new InputReader(System.in);
out = new PrintWriter(System.out);
}
solve(in, out);
out.close();
}
public static void solve(InputReader in, PrintWriter out) {
}
}
Basically this thing needs to be in xml, but I don't know how to write it properly, I thought writing ${filename} everywhere would do it, but it doesn't work. All in all, I want the name of the file to be written in places where I write "${filename}", how can I do it?

You can declare a template variable like this:
public class ${cursor}${type:newName} {
public ${type}() {
// constructor
}
}
Now if you use this as a template, both type occurrences will be updated by what you write when you edit it after template insertion.

Related

Why i get unicode from html?

I wrtite parser without third-party libraries. Get html code from web site - http://www.cnn.com/ - but some part of code has unicode instead symbols, for example: "\u003cbr/>Sign in to your TV service provider to get access to \u003cbr/>" i think it is problem with encode - how i can fix it? Sorry for my English. Thank you.
public class Main {
public static void main(String[] args) throws IOException {
String commandLine = Scraper.readLineFromConsole();
Reader reader = Scraper.getReader(commandLine);
Scraper.writeInFileFromURL(reader);
}
public static class Scraper {
public static void writeInFileFromURL(Reader out) {
Reader reader = out;
BufferedReader br = new BufferedReader(reader);
try {
PrintWriter writer = new PrintWriter("newFile.txt");
String htmltext;
while (br.ready()) {
htmltext = br.readLine();
writer.write(new String(htmltext));
}
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static String readLineFromConsole() {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String commandLine = null;
try {
commandLine = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return commandLine;
}
public static Reader getReader(String url)
throws IOException {
// Retrieve from Internet.
if (url.startsWith("http:") || url.startsWith("https:")) {
URLConnection conn = new URL(url).openConnection();
return new InputStreamReader(conn.getInputStream());
}
// Retrieve from file.
else {
return new FileReader(url);
}
}
}
}

how to acces other class method in java

I have two classes:
class actUI
public class ActUI extends javax.swing.JFrame{
//there are the other classes here
private static void writeToFile(java.util.List list, String path) {
BufferedWriter out = null;
try {
File file = new File(path);
out = new BufferedWriter(new FileWriter(file, true));
for (Object s : list) {
out.write((String) s);
out.newLine();
}
out.close();
} catch (IOException e) {
}
UniqueLineReader ULR = new UniqueLineReader();
ULR.setFileName(path);
}
//there are the other classes here
}
Class UniqueLineReader:
public class UniqueLineReader extends BufferedReader {
Set<String> lines = new HashSet<String>();
private Reader arg0;
public UniqueLineReader(Reader arg0) {
super(arg0);
}
#Override
public String readLine() throws IOException {
String uniqueLine;
while (lines.add(uniqueLine = super.readLine()) == false); //read until encountering a unique line
return uniqueLine;
}
public void setFileName(String filePath){
try {
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("test.txt");
UniqueLineReader br = new UniqueLineReader(new InputStreamReader(fstream));
String strLine;
// Read File Line By Line
PrintWriter outFile2 = new PrintWriter(new File("result.txt"));
String result = "";
List data = new ArrayList();
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println(strLine);
data.add(strLine);
}
writeToFile(data, "result.txt");
// Close the input stream
//in.close();
} catch (Exception e) {// Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
I want to acces UniqueLineReader from writeToFile method in actUI, but my code is not working, how can i do that with no error?, help me please.
Take a look at your code.
UniqueLineReader ULR = new UniqueLineReader(); // invalid constructor
ULR.setFileName(path);
There is no matching constructor for this. If you want to access writeToFile() from ActUI, Just change access modifier of writeToFile() to public now you can use following
UniqueLineReader.writeToFile(new ArrayList(), path);

br.readline() gets stuck while br.read() works

I am making a simple ftp client/server program which on command from the clients lists files, tells the current directory, downloads files
My client code works fine since i have already tested it with a working server. However the server that i have designed gets stuck in the run() function on the line String message = br.readline(); If instead i use the br.read(), then it works but i need command in form of a string to know which file i have to download whereas br.read() returns int. Here's my code, i have used threading.
public class Myserver {
static final int PortNumber = 108;
static ServerSocket MyService;
static Socket clientSocket = null;
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
File directory;
directory = new File(System.getProperty("user.home"));
try {
MyService = new ServerSocket(PortNumber);
String cd = directory.toString();
System.out.println(cd);
System.out.println("Listening on " + PortNumber);
while(true) {
clientSocket = MyService.accept();
Connecthandle a = new Connecthandle(clientSocket, directory);
a.run();
}
}
catch (IOException e) {
System.out.println(e);
}
}
static class Connecthandle extends Thread {
File Directory;
Socket clientsocket;
// Constructor for class
Connecthandle(Socket clients, File dir) {
clientsocket = clients;
Directory = dir;
}
// Works Fine
void listfiles() throws IOException {
String []Listfile = Directory.list();
String send = "";
for (int j = 0; j < Listfile.length; j++) {
send = send + Listfile[j] + ",";
}
DataOutputStream GoingOut = new DataOutputStream(clientsocket.getOutputStream());
GoingOut.writeBytes(send);
GoingOut.flush();
GoingOut.close();
}
// Works Fine
void currentdirectory() throws IOException {
String cd = Directory.toString();
String cdd = "resp," + cd;
System.out.println(cdd);
DataOutputStream GoingOut = new DataOutputStream(clientsocket.getOutputStream());
GoingOut.writeBytes(cdd);
GoingOut.flush();
GoingOut.close();
System.exit(0);
}
void sendfiles(String fileName) {
try {
File nfile = new File(fileName);
DataOutputStream GoingOut = new DataOutputStream(clientsocket.getOutputStream());
if ( (! nfile.exists()) || nfile.isDirectory() ) {
GoingOut.writeBytes("file not present");
} else {
BufferedReader br = new BufferedReader(new FileReader(nfile));
String line;
while ((line = br.readLine()) != null) {
line = br.readLine();
GoingOut.writeBytes(line+"\n");
}
GoingOut.flush();
GoingOut.close();
br.close();
}
} catch (IOException e) {
System.out.println("Unable to send!");
}
}
#SuppressWarnings("deprecation")
public void run() {
try {
DataInputStream comingin = new DataInputStream(clientsocket.getInputStream());
InputStreamReader isr = new InputStreamReader(comingin, "UTF-8");
BufferedReader br = new BufferedReader(isr);
System.out.println("here");
// if (br.ready())
String message = br.readLine(); // Code gets stuck here, if i use br.read() it works, but i need string output.
if (message.equals("listfiles\n")) {
listfiles();
} else if (message.equals("pwd")) {
currentdirectory();
} else if (message.contains("getfile,")) {
String fileName = new String(message.substring(8, message.length()));
sendfiles(fileName);
}
} catch (Exception e) {
e.printStackTrace();
}
finally {
try {
clientsocket.close();
} catch (IOException e) {}
}
}
}
}
If readLine() is blocking and you are sending data, you aren't sending a newline.

Why does the integer written to a file get read as a different value?

I've got a program where I need to generate an integer, write it to a text file and read it back the next time the program runs. After some anomalous behavior, I've stripped it down to setting an integer value, writing it to a file and reading it back for debugging.
totScore, is set to 25 and when I print to the console prior to writing to the file, I see a value of 25. However, when I read the file and print to the console I get three values...25, 13, and 10. Viewing the text file in notepad gives me a character not on the keyboard, so I suspect that the file is being stored in something other that int.
Why do I get different results from my write and read steps?
Is it not being written as an int? How are these values being stored in the file? Do I need to cast the read value as something else and convert it to an integer?
Consider:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.nio.file.*;
import java.nio.file.StandardOpenOption.*;
//
public class HedgeScore {
public static void main(String[] args) {
int totScore = 25;
OutputStream outStream = null; ///write
try {
System.out.println("totscore="+totScore);
BufferedWriter bw = new BufferedWriter(new FileWriter(new File("hedgescore.txt")));
bw.write(totScore);
bw.write(System.getProperty("line.separator"));
bw.flush();
bw.close();
}
catch(IOException f) {
System.out.println(f.getMessage());
}
try {
InputStream input = new FileInputStream("hedgescore.txt");
int data = input.read();
while(data != -1) {
System.out.println("data being read from file :"+ data);
data = input.read();
int prevScore = data;
}
input.close();
}
catch(IOException f) {
System.out.println(f.getMessage());
}
}
}
You're reading/writing Strings and raw data, but not being consistent. Why not instead read in Strings (using a Reader of some sort) and then convert to int by parsing the String? Either that or write out your data as bytes and read it in as bytes -- although that can get quite tricky if the file must deal with different types of data.
So either:
import java.io.*;
public class HedgeScore {
private static final String FILE_PATH = "hedgescore.txt";
public static void main(String[] args) {
int totScore = 25;
BufferedWriter bw = null;
try {
System.out.println("totscore=" + totScore);
bw = new BufferedWriter(new FileWriter(new File(
FILE_PATH)));
bw.write(totScore);
bw.write(System.getProperty("line.separator"));
bw.flush();
} catch (IOException f) {
System.out.println(f.getMessage());
} finally {
if (bw != null) {
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
InputStream input = null;
try {
input = new FileInputStream(FILE_PATH);
int data = 0;
while ((data = input.read()) != -1) {
System.out.println("data being read from file :" + data);
}
input.close();
} catch (IOException f) {
System.out.println(f.getMessage());
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
or:
import java.io.*;
public class HedgeScore2 {
private static final String FILE_PATH = "hedgescore.txt";
public static void main(String[] args) {
int totScore = 25;
PrintWriter pw = null;
try {
System.out.println("totscore=" + totScore);
pw = new PrintWriter(new FileWriter(new File(FILE_PATH)));
pw.write(String.valueOf(totScore));
pw.write(System.getProperty("line.separator"));
pw.flush();
} catch (IOException f) {
System.out.println(f.getMessage());
} finally {
if (pw != null) {
pw.close();
}
}
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(FILE_PATH));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException f) {
System.out.println(f.getMessage());
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

Remove new line when using printwriter

I am trying to print out any changes that is appended at the end of a log file, similar to tail log. But when printing it out with printwriter it will also print out a new line.
Instead of printing
test1
test2
it prints:
test1
test2
Code is as below. I tried with pwriter.print(line) instead of println but nothing is printed. Is there any way to remove the carriage return.
public class Lognow implements Runnable{
boolean execute = true;
InputStreamReader inputStreamReader;
BufferedReader bufferedReader;
PrintWriter pwriter;
public Lognow(){
PrintWriter pw = new PrintWriter(System.out, true);
try {
inputStreamReader = new InputStreamReader(new FileInputStream ("D:/app/logi.txt"));
bufferedReader = new BufferedReader (inputStreamReader);
String line = bufferedReader.readLine();
while(line!=null){
line = bufferedReader.readLine();
}
pwriter = pw;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
while( execute ) {
try {
String str="";
String line = bufferedReader.readLine();
if(line!=null) {
pwriter.println(line);
}
else {
try {
Thread.sleep( 500 );
}
catch( InterruptedException ex )
{
execute = false;
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args){
Lognow lognow = new Lognow();
lognow.run();
}
Don't use println(). Use print() instead, and flush().

Categories