I have an app which can download images from a website,
it runs perfectly, but there is only one thing that annoys me, it is CPU intensive.
here is my code, could anyone give any advice how to handle this?
thank you so much!
Task.java
public class Task implements Runnable {
private String url;
private int server;
public Task(String url, int server) {
this.url = url;
this.server = server;
}
#Override
public void run() {
android.os.Process
.setThreadPriority(android.os.Process.THREAD_PRIORITY_LESS_FAVORABLE);
int page = 1;
String r1 = "";
if (server == 1) {
r1 = getRaw(url);
} else if (server == 2) {
url = url + "page/";
r1 = getRaw(url + page);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String subs = url.substring(0, url.lastIndexOf('/') + 1);
List<String> a1 = getPackage(r1, server);
String t1 = getImageLink(r1, server);
String loc = DownloadXML.UNDUH + File.separator + a1.get(0)
+ File.separator + a1.get(1) + ' ' + a1.get(2);
File f1 = new File(loc);
if (!f1.exists())
f1.mkdirs();
getImage(loc, t1, page);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
page++;
if (server == 1) {
while (true) {
r1 = getRaw(subs + page);
t1 = getImageLink(r1, server);
if (t1 != null) {
getImage(loc, t1, page);
page++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
break;
}
}
return;
} else if (server == 2) {
int maxPage = Integer.parseInt(a1.get(3));
while (page <= maxPage) {
r1 = getRaw(subs + page);
t1 = getImageLink(r1, server);
if (t1 != null) {
getImage(loc, t1, page);
page++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
break;
}
}
return;
}
}
private String getRaw(String link) {
String raw = null;
try {
URL myUrl = new URL(link);
HttpURLConnection conn = (HttpURLConnection) myUrl.openConnection();
conn.setRequestProperty(
"User-Agent",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.29 Safari/537.36");
InputStreamReader is = new InputStreamReader(conn.getInputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
raw += line;
}
is.close();
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
return raw;
}
private List<String> getPackage(String raw, int server) {
List<String> pack = new ArrayList<String>();
switch (server) {
case 1:
Pattern pattern = Pattern
.compile("<span class=\"visible-desktop visible-tablet.+?</span>.+?<span class=\"visible-desktop visible-tablet.+?</span>");
Matcher matcher = pattern.matcher(raw);
String b = null;
while (matcher.find()) {
b = matcher.group();
if (b != null) {
String[] t = b.split("<[^>]*>");
for (int i = 0; i < t.length; i++) {
if (!t[i].isEmpty()) {
pack.add(t[i].trim());
}
}
}
}
break;
case 2:
Pattern pattern1 = Pattern
.compile("<div class=\"topbar_left\">.+?</a>.+?</a>");
Matcher matcher1 = pattern1.matcher(raw);
Pattern pPage = Pattern.compile("<div class=\"tbtitle dropdown_parent dropdown_right\"><div class=\"text\">[0-9]+ </div>");
Matcher mPage = pPage.matcher(raw);
while (matcher1.find()) {
String s = matcher1.group().trim();
s = s.replaceAll("<[^>]*>", "");
String[] temp = s.split("[:]+");
for (int i = 0; i < temp.length; i++) {
if (temp[i] != null)
if (i == 1) {
pack.add(temp[i].replaceAll("[a-zA-z]+", "").trim());
} else if (i == 2) {
pack.add("- "
+ temp[i].trim().replaceAll(
"[^a-zA-z0-9]+", "_"));
} else {
pack.add(temp[i].trim());
}
}
}
while (mPage.find()) {
pack.add(mPage.group().replaceAll("<[^>]*>", "").trim());
}
break;
}
return pack;
}
private String getImageLink(String raws, int server) {
/*
* Return image link
*/
switch (server) {
case 1:
Pattern pattern = Pattern.compile("http://img.+(jpg|png)");
Matcher matcher = pattern.matcher(raws);
while (matcher.find()) {
return matcher.group();
}
break;
case 2:
Pattern pattern1 = Pattern
.compile("http://manga.redhawkscans.com/content/comics/.+?(jpg|png)");
Matcher matcher1 = pattern1.matcher(raws);
while (matcher1.find()) {
if (matcher1.group().contains("thumb")) {
return null;
} else {
return matcher1.group();
}
}
break;
}
return null;
}
private void getImage(String loc, String link, int page) {
/*
* Get image and save it
*/
try {
URL url = new URL(link);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty(
"User-Agent",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.29 Safari/537.36");
String form = link.substring(link.lastIndexOf('.') + 1);
String p = "0";
if (page < 10) {
p += Integer.toString(page);
} else {
p = Integer.toString(page);
}
File f = new File(loc, p + '.' + form);
Bitmap bitmap = BitmapFactory.decodeStream(conn.getInputStream());
FileOutputStream fos = new FileOutputStream(f);
if (form == "jpg") {
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
} else {
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
}
conn.disconnect();
fos.flush();
fos.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
and in another class, I just call new Thread(new Task(link,server)).start() to start the threading.
A lot of code that uses RegExps working with large strings (web pages?)
converting images on the fly.
new URLConnection on every request.
Try to:
Test your RegExp's performance and work with it. Short and too complicated RegExps like [abc] is very slow on large strings.
Do you really need to recompress your bitmaps. May be it's better to store original stream to file rather than recompress it?
Create Connection pool or shared connection to increase connection time and minimize unneeded initializations.
Also you can try minimize thread priority to BACKGROUND:
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
Related
I need to update data from server every second. I create handle with AsyncTask, that repeats every second. This works, but about a minute it crushes with EOFException by reading from DataInputStream.
Handler
handler.postDelayed( new Runnable() {
#Override
public void run() {
tickListAdapter = new TickListAdapter(TickActivity.this,tickList);
tickListView.setAdapter(tickListAdapter);
AsyncTCPSend tcpSend= new AsyncTCPSend(address,serverPort, line);
tcpSend.execute();
Log.e(TAG,"update");
handler.postDelayed( this, 1000 );
}
},1000 );
AsyncTask
public class AsyncTCPSend extends AsyncTask<Void, Void, Void> {
String address;
int port;
String message;
String response=null;String lineRead = null;
Socket socket;
int count=1;
OutputStream os;
DataInputStream dis;
AsyncTCPSend(String addr, int p, String mes) {
address = addr;
port = p;
message = mes;
}
#Override
protected Void doInBackground(Void... params) {
socket = null;
try {
socket = new Socket(address, port);
os = socket.getOutputStream();
dis = new DataInputStream(socket.getInputStream());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (!isConnect){
if (connect()){
isConnect = true;
Log.e("CLIENT","now is connected");
getTick();
}
}
return null;
}
public boolean connect(){
try {
Log.e("CLIENT","CONNECTED");
String command = "AUTH_START";
byte[] queryBody = null;
queryBody = command.getBytes("UTF-16LE");
byte[] message = new byte[queryBody.length];
for (int i = 0; i < message.length; ++i)
os.write(message,0,message.length);
Log.e(TAG,"AUTH_START");
String srv = null;
srv = function();
if (srv != null){
if (srv.equals("Error")){
Log.e("CLIENT","Error");
return false;
} else {
String auth_answer = "AUTH_ANSWER";
byte[] authBody = auth_answer.getBytes("UTF-16LE");
Log.e(TAG,"AUTH_ANSWER");
os.write(authBody,0,authBody.length);
srv = function();
if (srv.equals("Error")){
Log.e("CLIENT","Error");
return false;
} else {
Log.e(TAG,"AUTH SUCCESS!!!");
return true;
}
}
} else {
return false;
}
}
catch (UnknownHostException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public String getTick(){
String tick = "TICK";
try {
tickBody = tick.getBytes("UTF-16LE");
os.write(tickBody,0,tickBody.length);
String srv = function();
return srv;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
String function(){
String srv = null;
int len = 0;
try {
len = dis.readInt(); //EOFException is here!!!!
byte[] data = new byte[1024];
if (len > 0) {
dis.read(data, 0, data.length);
}
String out = new String(data,"UTF-16");
if (out.indexOf("Done")>0){
if (out.indexOf("STAT")>0 ||out.indexOf("AST")>0){
srv = out;
}
else {
srv = out.substring(out.indexOf("SRV")+9,out.indexOf("SRV")+41);
}
} else {
srv = "Error";
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return srv;
}
#Override
protected void onPostExecute(Void result) {
Log.e("CLIENT","onPostExecute");
super.onPostExecute(result);
}
}
}
Anybody know why appear EOFException about a minute? How to avoid?
P.S. To obtain the necessary information from the server, I must first pass authentication
Why this exception occurs?
According to Docs
Signals that an end of file or end of stream has been reached unexpectedly during input.
This exception is mainly used by data input streams to signal end of stream. Note that many other input operations return a special value on end of stream rather than throwing an exception.
look upon this answer
The problem was solved by changing the method. I added two threads for output and input inside AsyncTask
I have built a chat application in Android powered by sockets. The messages send and receive fine, so long as the user does not send messages with special characters, ie. Hey, it's me, will not work, but Hey its me, will, the comma and apostrophe prevent the message from being delivered.
I attempted using URLEncoder, but that did not allow the unique characters to be sent.
Sending message method:
public String sendMessage(String username, String tousername, String message, String campaign_id, String location_id)
throws UnsupportedEncodingException {
String params = "username=" + URLEncoder.encode(this.username, "UTF-8")
+ "&password=" + URLEncoder.encode(this.password, "UTF-8")
+ "&to=" + URLEncoder.encode(tousername, "UTF-8")
+ "&message=" + URLEncoder.encode(message, "UTF-8")
+ "&campaign_id=" + URLEncoder.encode(campaign_id, "UTF-8")
+ "&location_id=" + URLEncoder.encode(location_id, "UTF-8")
+ "&action=" + URLEncoder.encode("sendMessage", "UTF-8")
+ "&gcmregid=" + gcmRegistrationID
+ "&";
Log.i("PARAMS", params);
return socketOperator.sendHttpRequest(params);
}
with
SocketerInterface socketOperator = new Socketer(this);
and Socketer class as:
public class Socketer implements SocketerInterface {
// Have to set the proper ports that apache is runnign on as well as your
// computers IP address: ie. ip:4430 or 800
Global ipAddress = new Global();
private final String AUTHENTICATION_SERVER_ADDRESS = "http://"
// + ipAddress.getIpAddress() + ":80/AndroidChatterDatabase/"; // Google Compute Engine Access
//+ ipAddress.getIpAddress() + ":4430/AndroidChatterDatabase/"; // Localhost access
+ ipAddress.getFeastChatServer(); // For Heroku access
private int listeningPort = 0;
private static final String HTTP_REQUEST_FAILED = null;
private HashMap<InetAddress, Socket> sockets = new HashMap<InetAddress, Socket>();
private ServerSocket serverSocket = null;
private boolean listening;
private class ReceiveConnection extends Thread {
Socket clientSocket = null;
public ReceiveConnection(Socket socket) {
this.clientSocket = socket;
Socketer.this.sockets.put(socket.getInetAddress(), socket);
}
#Override
public void run() {
try {
// PrintWriter out = new
// PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
Log.v("XML MESSAGE", inputLine);
if (inputLine.equals("exit") == false) {// as long as have
// noted exited yet,
// will continuing
// reading in
Log.v("XML MESSAGE", inputLine);
// appManager.messageReceived(inputLine);
} else {
clientSocket.shutdownInput();
clientSocket.shutdownOutput();
clientSocket.close();
Socketer.this.sockets.remove(clientSocket
.getInetAddress());
}
}
} catch (IOException e) {
Log.e("ReceiveConnection.run: when receiving connection ", "");
}
}
}
public Socketer(Manager appManager) {
}
public String sendHttpRequest(String params) {
URL url;
String result = new String();
try {
url = new URL(AUTHENTICATION_SERVER_ADDRESS);
HttpURLConnection connection;
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
PrintWriter out = new PrintWriter(connection.getOutputStream());
out.println(params);
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
result = result.concat(inputLine);
}
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (result.length() == 0) {
result = HTTP_REQUEST_FAILED;
}
// This is the output of the datastream from the server ie. <data>
// (bunch of data...etc) </data>
// Testing to remove <head/> tag from Google App Engine
//return result.replace("<head/>","");
return result;
}
public int startListening(int portNo) {
listening = true;
try {
serverSocket = new ServerSocket(portNo);
this.listeningPort = portNo;
} catch (IOException e) {
// e.printStackTrace();
this.listeningPort = 0;
return 0;
}
while (listening) {
try {
new ReceiveConnection(serverSocket.accept()).start();
} catch (IOException e) {
// e.printStackTrace();
return 2;
}
}
try {
serverSocket.close();
} catch (IOException e) {
Log.e("Exception server socket",
"Exception when closing server socket");
return 3;
}
return 1;
}
public void stopListening() {
this.listening = false;
}
public void exit() {
for (Iterator<Socket> iterator = sockets.values().iterator(); iterator
.hasNext();) {
Socket socket = (Socket) iterator.next();
try {
socket.shutdownInput();
socket.shutdownOutput();
socket.close();
} catch (IOException e) {
}
}
sockets.clear();
this.stopListening();
}
public int getListeningPort() {
return this.listeningPort;
}
}
How can I format/encode to allow sending these messages?
Java uses UTF-16 for internal String representation, but it looks like you are using UTF-8, but you aren't doing anything special to convert it from UTF-8 when reading it from BufferedReader. In the params, try specifying UTF-16 instead.
From the Java String documentation:
A String represents a string in the UTF-16 format
public class PreviewDownload extends AsyncTask<String, Void, String> {
public static final String TAG = "PreviewDownload";
public String inputPath = null;
public String outputFolder = null;
public IRIssue issue = null;
#Override
protected String doInBackground(String... parms) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
issue = Broker.model.issueDataStore.getIRIssue(parms[0]);
outputFolder = IRConstant.issueFolder(issue.year, issue.month, issue.day, issue.pubKey);
try {
inputPath = IRConstant.downloadFile(issue.year, issue.month, issue.day, issue.pubKey, "preview", "0");
URL url = new URL(inputPath);
Log.d (TAG,"input: " + inputPath);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
return null;
// return "Server returned HTTP " + connection.getResponseCode()
// + " " + connection.getResponseMessage();
// download the file
input = connection.getInputStream();
output = new FileOutputStream(outputFolder + "/preview.zip");
Log.d (TAG,"output: " + output);
byte data[] = new byte[1024];
int count;
while ((count = input.read(data)) != -1) {
output.write(data, 0, count);
}
} catch (Exception e) {
// return e.toString();
return null;
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return outputFolder;
}
#Override
protected void onPostExecute(String outputFolder) {
// TODO Auto-generated method stub
super.onPostExecute(outputFolder);
if (outputFolder != null) {
File zipFile = new File (outputFolder + "/preview.zip");
if (Utils.unzip(outputFolder,outputFolder + "/preview.zip" )) {
zipFile.delete();
issue.isThumbDownloaded = 1;
} else {
issue.isThumbDownloaded = 0;
}
} else {
Toast.makeText(Broker.launcherActivity.getBaseContext(), R.string.wordCantDownload, Toast.LENGTH_LONG).show();
issue.isThumbDownloaded = 0;
}
issue.updateProgress(issue.progress);
}
}
Here is the downloader I implemented , the problem is , when the network lost, the output become null and show error message, however, if I would like to retry two times before showing error message, are there any way to do this? If I perfer not to pass in an object instead of string ,is it not recommended? thanks
What prevents you from re-instanciating and re-executing a "Downloader" from your catch blocks in case of errors ?
You could use a single common shared object between dowloader instances to count the attempts, or better, pass a parameter to each of them. In the catch block, you would then retry if you didn't reach the limit, and increase the value passed to a new downloader... Something recursive.
int expectedLength = connection.getContentLength();
can you compare with the expectedLength & downloaded length and retry?
I have a problem. I met only once. My code algoritm is designed requesting only one time.
But a request was received twice by server. I must produce a solution.
I think, this problem likes this url But I cant find anything(bug or question) about httpurlconnection?
Device's Android Version is 4.0.3 and Connection Method is GET.
try {
String encoding = session.getPlatform().getEncodingIse();
if (TradeUtil.isApachiClientActive()) {
HttpResponse hr = XHttpClientFactory.getConnectionResponse(session.getPlatform(), TradeServiceType.ISE, command);
if (!session.getPlatform().isUseStaticEncodingForIse()) {
encoding = XHttpClientFactory.getEncoding(hr, encoding);
}
strRtn = TradeUtil.getResponse(hr.getEntity().getContent(), encoding);
} else {
con = TradeUtil.createConnection(session.getPlatform(), TradeServiceType.ISE, command);
if (!session.getPlatform().isUseStaticEncodingForIse()) {
encoding = TradeUtil.getEncoding(con, session.getPlatform().getEncodingIse());
}
strRtn = TradeUtil.getResponse(con.getInputStream(), encoding);
}
} catch (Exception e) {
TradeUtil.toConsole(e);
response.getResponseResult().setResponseCode(ResponseResult.CONNECTION_ERROR);
response.getResponseResult().setDescription(e.getMessage());
try {
if (con != null)
con.disconnect();
} catch (Exception ex) {
}
return response;
}
public static HttpURLConnection createConnection(Platform platform,
TradeServiceType serviceType, String command) throws Exception {
command = command + "&MTXTimeAnd=" + Calendar.getInstance().getTimeInMillis(); // Cachlemeyi
// Engellemek
// için
TradeUtil.initSSLContext(); // Zoom ve ustundeki makinalar için SSL
// handshake için trust manager set etmek
// gerekiyor.
System.setProperty("http.keepAlive", "false");// Yatirim finansman +
// Android 2.2 Bug için
// gerekli
System.setProperty("https.keepAlive", "false"); // Yatirim finansman +
// Android 2.2 Bug için
// gerekli
HttpURLConnection con;
String methodType;
String encoding;
String strAdd = null;
if (serviceType.equals(TradeServiceType.ISE)) {
strAdd = platform.getIseServiceAdress();
methodType = platform.getIseConnectionMethodType();
encoding = platform.getEncodingIse();
} else if (serviceType.equals(TradeServiceType.TURKDEX)) {
strAdd = platform.getTurkdexServiceAdress();
methodType = platform.getTurkdexConnectionMethodType();
encoding = platform.getEncodingTurkdex();
} else {
throw new IllegalArgumentException("hatali service tipi");
}
if (methodType.equalsIgnoreCase("GET")) {
strAdd = strAdd + "?" + command;
}
URL adress = new URL(strAdd);
if (adress.getProtocol().equalsIgnoreCase("https")) {
con = (HttpsURLConnection) adress.openConnection();
((HttpsURLConnection) con).setHostnameVerifier(new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
} else {
con = (HttpURLConnection) adress.openConnection();
}
con.setUseCaches(false);
con.setReadTimeout(platform.getConnectionTimeout());
con.setConnectTimeout(platform.getConnectionTimeout());
if (methodType.equalsIgnoreCase("POST")) {
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestMethod("POST");
OutputStreamWriter osw = null;
try {
osw = new OutputStreamWriter(con.getOutputStream(), encoding);
osw.write(command);
osw.flush();
osw.close();
osw = null;
} catch (Exception ex) {
TradeUtil.toConsole(ex);
try {
if (osw != null)
osw.close();
} catch (Exception ex2) {
TradeUtil.toConsole(ex);
}
throw ex;
}
} else {
}
return con;
}
Since Google analytics can raise many privacy concerns, I implemented an events logger.
My first idea is to track user's generated events into a logfile and then send them back to the server that will perform the analysis of data for the System Administrator and Application Engineers.
For the moment the idea is to instantiate the Logger into an Application or a Service class and use those elements onCreate and onDestroy to safely handle the LogFile.
The solution is quite simple:
Open file
Append to it every time an event is generated
Once the a MAX_NUM_LINES is reached, send the log to the server (possibly I'll zip the text file I am generating)
I wonder if there's anything already baked there in the wild I am unaware of that you might know (something like ACRA).
Every contribution will be appreciated.
Here my implementation.
However any better version is much appreciated.
The TSG objet is just a static class that I use as time manager.
Use the code and improve it as long as you repost / edit the modifications.
public class Logger {
private BufferedWriter logFile;
private String nameFile;
public int fileLines;
private File fTemp;
private timeStampGenerator TSG;
private int LOG_LINES_LIMIT = 100;
private Object mutex;
public enum EventType {
BUTTON_PRESSED,
PAGE_VIEWED,
LOADED_ACTIVITY,
GENERIC_EVENT
}
public Logger (String fileName) throws IOException {
nameFile = fileName;
createLogFile();
fileLines = countLines();
TSG = new timeStampGenerator();
// This is our mutex to access to the file
mutex = new Object();
}
public void createLogFile() throws IOException{
fTemp = new File (nameFile);
if (!fTemp.exists()) {
fTemp.createNewFile();
}
logFile = new BufferedWriter(new FileWriter(nameFile, true));
}
public void LogEvent(EventType event, String comment, String value) {
String line = "";
line += TSG.getTimestampMillis();
line += ",";
line += event.name();
line += ",";
if (comment != "") {
line += comment.replaceAll(",", ";");
} else {
line += " ";
}
line += ",";
if (value != "") {
line += value.replaceAll(",", ";");
} else {
line += " ";
}
line += "\n";
synchronized (mutex) {
try {
logFile.append(line);
} catch (IOException e) {
// Do wathever you want here
}
fileLines++;
}
}
public int countLines() //throws IOException
{
InputStream is;
try {
is = new BufferedInputStream(new FileInputStream(nameFile));
} catch (FileNotFoundException e1) {
//let's consider it an empty file
return 0;
}
int count = 0;
boolean empty = true;
try {
int readChars = 0;
byte[] c = new byte[1024];
while ((readChars = is.read(c)) != -1) {
empty = false;
for (int i = 0; i < readChars; ++i) {
if (c[i] == '\n')
++count;
}
}
} catch(IOException e) {
// Do wathever you want here
}
try {
is.close();
} catch (IOException e) {
// Do wathever you want here
}
return (count == 0 && !empty) ? 1 : count;
}
public boolean isLimitReached() {
return (fileLines >= LOG_LINES_LIMIT);
}
public void close () {
flush();
try {
logFile.close();
} catch (IOException e) {
// Do wathever you want here
}
}
/**
* clear the content of the file
*/
public void clearFile() {
synchronized (mutex) {
if ( fTemp.delete() ) {
try {
createLogFile();
} catch (IOException e1) {
// Do wathever you want here
}
}
}
}
/**
* Get the full content of the file
* #return the content
*/
public String getContent() {
StringBuffer fileData = new StringBuffer();
synchronized (mutex) {
try {
BufferedReader reader = new BufferedReader(new FileReader( nameFile ));
char[] buf = new char[1024];
int numRead = 0;
while ((numRead = reader.read(buf)) != -1) {
String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
}
reader.close();
} catch (IOException e) {
// Do wathever you want here
}
}
return fileData.toString();
}
public void flush() {
try {
logFile.flush();
} catch (IOException e) {
// Do wathever you want here
}
}
}