I have a dynamic web project in eclipse. When I'm executing just WordFreq.java it works. If I want to execute same code in MyServlet.java > doGet method, I get this error: HTTP Status 500 - text.txt (The system cannot find the file specified).
I copied my file (text.txt) everywhere :
The project root folder
The WebContent folder
The src folder
Any subdirectory in my project.
and still get this error.
Note: my workspace is in D:/.... and my Apache server is on C:/...
I tried to change to full path but still doesn't work.
WordFreq.java
package cpd;
import java.io.*;
import java.util.Scanner;
public class WordFreq {
public static void main(String[] args) throws IOException {
File file1 = new File("text.txt");
BufferedReader in = new BufferedReader(new FileReader(file1));
String content = new Scanner(file1).useDelimiter("\\Z").next();
CezarBun cezar = new CezarBun();
System.out.println(cezar.criptare(content, 3));
System.out.println("Frecventa literelor");
System.out.println();
int nextChar;
char ch;
double[] count = new double[26];
while ((nextChar = in.read()) != -1) {
ch = ((char) nextChar);
if (ch >= 'a' && ch <= 'z') {
count[ch - 'a']++;
}
}
for (int i = 0; i < 26; i++) {
System.out.printf("%c %d", i + 'a', (int) count[i]);
System.out.println("Frecventa: " + count[i] / file1.length() * 100 + "%");
}
in.close();
try {
/*create a buffered reader that connects to the console, we use it so we can
read lines*/
BufferedReader in2 = new BufferedReader(new InputStreamReader(System.in));
//read a line from the console
String lineFromInput = in2.readLine();
//create an print writer for writing to a file
PrintStream out = new PrintStream(new FileOutputStream("output.txt"));
System.setOut(out);
//output to the file a line
out.println(lineFromInput);
//close the stream
out.close();
} catch (IOException e1) {
System.out.println("Error during reading/writing");
}
}
}
MyServlet.java
package cpd;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.Scanner;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class MyServlet
*/
#WebServlet("/MyServlet")
public class MyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public MyServlet() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("A pornit servlet-ul" + "<br />");
//inceput wordfreq
File file1 = new File("text.txt");
BufferedReader in = new BufferedReader(new FileReader(file1));
String content = new Scanner(file1).useDelimiter("\\Z").next();
CezarBun cezar = new CezarBun();
System.out.println(cezar.criptare(content, 3));
System.out.println("Frecventa literelor");
System.out.println();
int nextChar;
char ch;
double[] count = new double[26];
while ((nextChar = in.read()) != -1) {
ch = ((char) nextChar);
if (ch >= 'a' && ch <= 'z') {
count[ch - 'a']++;
}
}
for (int i = 0; i < 26; i++) {
System.out.printf("%c %d", i + 'a', (int) count[i]);
System.out.println(" Frecventa: " + count[i] / file1.length() * 100 + "%");
}
in.close();
try {
//create a buffered reader that connects to the console, we use it so we can read lines
BufferedReader in2 = new BufferedReader(new InputStreamReader(System.in));
//read a line from the console
String lineFromInput = in2.readLine();
//create an print writer for writing to a file
PrintStream out2 = new PrintStream(new FileOutputStream("output.txt"));
System.setOut(out2);
//output to the file a line
out2.println(lineFromInput);
//close the file (VERY IMPORTANT!)
out2.close();
} catch (IOException e1) {
System.out.println("Error during reading/writing");
}
//sfarsit wordfreq
// freq = new WordFreqBun();
//freq.wf();
out.print("<br />");
out.print("<a href='http://localhost:8080/CpdApplication/'>Inapoi la meniu</a>");
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
You can access your file as a resource using the ServletContext.getResourceAsStream(), the file can be located anywhere in your web application. It is recommended to keep it under the /WEB-INF directory if you don't want browers being able to access it.
ServletContext context = getServletContext();
InputStream is = context.getResourceAsStream("/file.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(is));
ServletContext.getResource() : Returns a URL to the resource that is mapped to the given path.
ServletContext.getResourceAsStream() :
Returns the resource located at the named path as an InputStream object.
Related
Trying to run a java program through Powershell. I go to my directory and use javac Part1.java and then to run the class I use java Part1 but it gives me this error Error: Could not find or load main class Part1 Here is the code in Part1.java which takes a basic .in text file and does some cool stuff with the each line in the .in document:
package comp2402a1;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Iterator;
import java.util.*;
public class Part1 {
/**
* Your code goes here - see Part0 for an example
* #param r the reader to read from
* #param w the writer to write to
* #throws IOException
*/
public static void doIt(BufferedReader r, PrintWriter w) throws IOException {
// Your code goes here - see Part0 for an example
SortedSet<String> s = new TreeSet<String>();
for (String line = r.readLine(); line != null; line = r.readLine()) {
s.add(line);
}
for (String text : s) {
w.println(text);
}
}
/**
* The driver. Open a BufferedReader and a PrintWriter, either from System.in
* and System.out or from filenames specified on the command line, then call doIt.
* #param args
*/
public static void main(String[] args) {
try {
BufferedReader r;
PrintWriter w;
if (args.length == 0) {
r = new BufferedReader(new InputStreamReader(System.in));
w = new PrintWriter(System.out);
} else if (args.length == 1) {
r = new BufferedReader(new FileReader(args[0]));
w = new PrintWriter(System.out);
} else {
r = new BufferedReader(new FileReader(args[0]));
w = new PrintWriter(new FileWriter(args[1]));
}
long start = System.nanoTime();
doIt(r, w);
w.flush();
long stop = System.nanoTime();
System.out.println("Execution time: " + 10e-9 * (stop-start));
} catch (IOException e) {
System.err.println(e);
System.exit(-1);
}
}
}
It is because of the package comp2402a1. Java expects Part1 class file to be on the
comp2402a1 folder.
Create that folder and put the class file (runnning like $ java comp2402a1/Part1) or remove the package from the source code.
In my quest to create a simple Java program to extract tweets from Twitter's streaming API, I have modified this (http://cotdp.com/dl/TwitterConsumer.java) code snippet to work with the OAuth method. The result is the below code, which when executed, throws a Connection Refused Exception.
I am aware of Twitter4J however I want to create a program that relies least on other APIs.
I have done my research and it looks like the oauth.signpost library is suitable for Twitter's streaming API. I have also ensured my authentication details are correct. My Twitter Access level is 'Read-only'.
I couldn't find a simple Java example that shows how to use the streaming API without relying on e.g. Twitter4j.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
/**
* A hacky little class illustrating how to receive and store Twitter streams
* for later analysis, requires Apache Commons HTTP Client 4+. Stores the data
* in 64MB long JSON files.
*
* Usage:
*
* TwitterConsumer t = new TwitterConsumer("username", "password",
* "http://stream.twitter.com/1/statuses/sample.json", "sample");
* t.start();
*/
public class TwitterConsumer extends Thread {
//
static String STORAGE_DIR = "/tmp";
static long BYTES_PER_FILE = 64 * 1024 * 1024;
//
public long Messages = 0;
public long Bytes = 0;
public long Timestamp = 0;
private String accessToken = "";
private String accessSecret = "";
private String consumerKey = "";
private String consumerSecret = "";
private String feedUrl;
private String filePrefix;
boolean isRunning = true;
File file = null;
FileWriter fw = null;
long bytesWritten = 0;
public static void main(String[] args) {
TwitterConsumer t = new TwitterConsumer(
"XXX",
"XXX",
"XXX",
"XXX",
"http://stream.twitter.com/1/statuses/sample.json", "sample");
t.start();
}
public TwitterConsumer(String accessToken, String accessSecret, String consumerKey, String consumerSecret, String url, String prefix) {
this.accessToken = accessToken;
this.accessSecret = accessSecret;
this.consumerKey = consumerKey;
this.consumerSecret = consumerSecret;
feedUrl = url;
filePrefix = prefix;
Timestamp = System.currentTimeMillis();
}
/**
* #throws IOException
*/
private void rotateFile() throws IOException {
// Handle the existing file
if (fw != null)
fw.close();
// Create the next file
file = new File(STORAGE_DIR, filePrefix + "-"
+ System.currentTimeMillis() + ".json");
bytesWritten = 0;
fw = new FileWriter(file);
System.out.println("Writing to " + file.getAbsolutePath());
}
/**
* #see java.lang.Thread#run()
*/
public void run() {
// Open the initial file
try { rotateFile(); } catch (IOException e) { e.printStackTrace(); return; }
// Run loop
while (isRunning) {
try {
OAuthConsumer consumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret);
consumer.setTokenWithSecret(accessToken, accessSecret);
HttpGet request = new HttpGet(feedUrl);
consumer.sign(request);
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(request);
BufferedReader reader = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
while (true) {
String line = reader.readLine();
if (line == null)
break;
if (line.length() > 0) {
if (bytesWritten + line.length() + 1 > BYTES_PER_FILE)
rotateFile();
fw.write(line + "\n");
bytesWritten += line.length() + 1;
Messages++;
Bytes += line.length() + 1;
}
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Sleeping before reconnect...");
try { Thread.sleep(15000); } catch (Exception e) { }
}
}
}
}
I tried to simulate the code and found that the error was very simple. You should use https instead of http in the url :)
This is a java code I search from the internet: http://avery-leo.iteye.com/blog/298724
Its goal is to get the CPU usage and memory info in the Linux System. I compiled it in eclipse and found two errors as follows:
private Config config=Config.getInstance();
SnmpUtil util=new SnmpUtil();
which I also mark in bold in the note part.
I think these two errors are caused by the lack of class Config and SnmpUtil, I tried to search and download a config.jar from the Internet and add it to the lib, but still it does not work!! I need your help!!
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.util.StringTokenizer;
import org.apache.log4j.Logger;
/**
* To get the cpu usage and memory in Linux system
*
* <p>
*/
public final class LinuxSystemTool implements Runnable{
private Logger log = Logger.getLogger(LinuxSystemTool.class);
private Config config=Config.getInstance(); //**Error when compiled**
/**
* get memory by used info
*
* #return int[] result
*
* result.length==4; int[0]=MemTotal;int[1]=MemFree;
* int[2]=SwapTotal;int[3]=SwapFree;
* #throws IOException
* #throws InterruptedException
*/
public void run() {
// TODO Auto-generated method stub
while (true) {
try {
exec();
Thread.sleep(config.getThreadTime());
} catch (Exception e) {
// TODO Auto-generated catch block
log.error("Performance Monitoring error:"+e.getMessage());
e.printStackTrace();
}
}
}
public void exec() throws Exception {
// ServerStatus ss = new ServerStatus();
InetAddress inet = InetAddress.getLocalHost();
System.out.println("Performance Monitoring ip:"+inet.toString());
String ip=inet.toString().substring(inet.toString().indexOf("/")+1);
log.info("Performance Monitoring ip:"+ip);
int[] memInfo = LinuxSystemTool.getMemInfo();
System.out.println("MemTotal:" + memInfo[0]);
System.out.println("MemFree:" + memInfo[1]);
SnmpUtil util=new SnmpUtil(); //**Error when compiled**
util.setCPU(getCpuInfo());
// util.setDISK(1);
util.setMEM(memInfo[0]/memInfo[1]);
util.setIP(ip);
}
public static int[] getMemInfo() throws IOException, InterruptedException {
File file = new File("/proc/meminfo");
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(file)));
int[] result = new int[4];
String str = null;
StringTokenizer token = null;
while ((str = br.readLine()) != null) {
token = new StringTokenizer(str);
if (!token.hasMoreTokens())
continue;
str = token.nextToken();
if (!token.hasMoreTokens())
continue;
if (str.equalsIgnoreCase("MemTotal:"))
result[0] = Integer.parseInt(token.nextToken());
else if (str.equalsIgnoreCase("MemFree:"))
result[1] = Integer.parseInt(token.nextToken());
else if (str.equalsIgnoreCase("SwapTotal:"))
result[2] = Integer.parseInt(token.nextToken());
else if (str.equalsIgnoreCase("SwapFree:"))
result[3] = Integer.parseInt(token.nextToken());
}
return result;
}
/**
* get memory by used info
*
* #return float efficiency
* #throws IOException
* #throws InterruptedException
*/
public static float getCpuInfo() throws IOException, InterruptedException {
File file = new File("/proc/stat");
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(file)));
StringTokenizer token = new StringTokenizer(br.readLine());
token.nextToken();
int user1 = Integer.parseInt(token.nextToken());
int nice1 = Integer.parseInt(token.nextToken());
int sys1 = Integer.parseInt(token.nextToken());
int idle1 = Integer.parseInt(token.nextToken());
Thread.sleep(1000);
br = new BufferedReader(
new InputStreamReader(new FileInputStream(file)));
token = new StringTokenizer(br.readLine());
token.nextToken();
int user2 = Integer.parseInt(token.nextToken());
int nice2 = Integer.parseInt(token.nextToken());
int sys2 = Integer.parseInt(token.nextToken());
int idle2 = Integer.parseInt(token.nextToken());
return (float) ((user2 + sys2 + nice2) - (user1 + sys1 + nice1))
/ (float) ((user2 + nice2 + sys2 + idle2) - (user1 + nice1
+ sys1 + idle1));
}
/**
*
* <p>
*
* #author
* </p>
* #date
*/
public static void main(String[] args) throws Exception {
int[] memInfo = LinuxSystemTool.getMemInfo();
System.out.println("MemTotal:" + memInfo[0]);
System.out.println("MemFree:" + memInfo[1]);
System.out.println("SwapTotal:" + memInfo[2]);
System.out.println("SwapFree:" + memInfo[3]);
System.out.println("CPU use ratio:" + LinuxSystemTool.getCpuInfo());
}
}
You need snmp4j jar for snmp related java development. you can get if from here.
Hope this will work for you.
I have 3 methods
for open file
for read file
for return things read in method read
this my code :
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication56;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.rmi.RemoteException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author x
*/
public class RemoteFileObjectImpl extends java.rmi.server.UnicastRemoteObject implements RemoteFileObject
{
public RemoteFileObjectImpl() throws java.rmi.RemoteException {
super();
}
File f = null;
FileReader r = null;
BufferedReader bfr = null;
String output = "";
public void open(String fileName) {
//To read file passWord
f = new File(fileName);
}
public String readLine() {
try {
String temp = "";
String newLine = System.getProperty("line.separator");
r = new FileReader(f);
while ((temp = bfr.readLine()) != null) {
output += temp + newLine;
bfr.close();
}
}
catch (IOException ex) {
ex.printStackTrace();
}
return output;
}
public void close() {
try {
bfr.close();
} catch (IOException ex) {
}
}
public static void main(String[]args) throws RemoteException{
RemoteFileObjectImpl m = new RemoteFileObjectImpl();
m.open("C:\\Users\\x\\Documents\\txt.txt");
m.readLine();
m.close();
}
}
But it does not work.
What do you expect it to do, you are not doing anything with the line you read, just
m.readLine();
Instead:
String result = m.readLine();
or use the output variable that you saved.
Do you want to save it to a variable, print it, write it to another file?
Update: after your update in the comments:
Your variable bfr is never created/initialized. You are only doing this:
r = new FileReader(f);
so bfr is still null.
You should do something like this instead:
bfr = new BufferedReader(new FileReader(f));
I have a requirement, for example, there will be number of .txt files in one loation c:\onelocation. I want to write the content to another location in txt format. This part is pretty easy and straight forward. But there is speed breaker here.
There will be time interval take 120 seconds. Read the files from above location and write it to another files with formate txt till 120secs and save the file with name as timestamp.
After 120sec create one more files with that timestamp but we have to read the files were cursor left in previous file.
Please can you suggest any ideas, if code is provided that would be also appreciable.
Thanks Damu.
How about this? A writer that automatically changes where it is writing two every 120 seconds.
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TimeBoxedWriter extends Writer {
private static DateFormat FORMAT = new SimpleDateFormat("yyyyDDDHHmm");
/** Milliseconds to each time box */
private static final int TIME_BOX = 120000;
/** For testing only */
public static void main(String[] args) throws IOException {
Writer w = new TimeBoxedWriter(new File("."), "test");
// write one line per second for 500 seconds.
for(int i = 0;i < 500;i++) {
w.write("testing " + i + "\n");
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {}
}
w.close();
}
/** Output folder */
private File dir_;
/** Timestamp for current file */
private long stamp_ = 0;
/** Stem for output files */
private String stem_;
/** Current output writer */
private Writer writer_ = null;
/**
* Create new output writer
*
* #param dir
* the output folder
* #param stem
* the stem used to generate file names
*/
public TimeBoxedWriter(File dir, String stem) {
dir_ = dir;
stem_ = stem;
}
#Override
public void close() throws IOException {
synchronized (lock) {
if (writer_ != null) {
writer_.close();
writer_ = null;
}
}
}
#Override
public void flush() throws IOException {
synchronized (lock) {
if (writer_ != null) writer_.flush();
}
}
private void rollover() throws IOException {
synchronized (lock) {
long now = System.currentTimeMillis();
if ((stamp_ + TIME_BOX) < now) {
if (writer_ != null) {
writer_.flush();
writer_.close();
}
stamp_ = TIME_BOX * (System.currentTimeMillis() / TIME_BOX);
String time = FORMAT.format(new Date(stamp_));
writer_ = new FileWriter(new File(dir_, stem_ + "." + time
+ ".txt"));
}
}
}
#Override
public void write(char[] cbuf, int off, int len) throws IOException {
synchronized (lock) {
rollover();
writer_.write(cbuf, off, len);
}
}
}
Use RamdomAccessFile in java to move the cursor within the file.
Before start copying check the file modification/creation(in case of new files) time, if less than 2 mins then only start copying or else skip it.
Keep a counter of no.of bytes/lines read for each file. move the cursor to that position and read it from there.
You can duplicate the file rather than using reading and writing operations.
sample code:
FileChannel ic = new FileInputStream("<source file location>")).getChannel();
FileChannel oc = new FileOutputStream("<destination location>").getChannel();
ic.transferTo(0, ic.size(), oc);
ic.close();
oc.close();
HTH
File io is simple in java, here is an example I found on the web of copying a file to another file.
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Copy {
public static void main(String[] args) throws IOException {
File inputFile = new File("farrago.txt");
File outputFile = new File("outagain.txt");
FileReader in = new FileReader(inputFile);
FileWriter out = new FileWriter(outputFile);
int c;
while ((c = in.read()) != -1)
out.write(c);
in.close();
out.close();
}
}