How do I close this file writer? (Java, Bukkit) - java

try {
FileWriter fw = new FileWriter("plugins/TestMessage/messages.txt", true);
} catch (IOException e) {
e.printStackTrace();}
}
Hey guys, I know this may sound noobish but how do I close this FileWriter. The code is in java. I have an onDisable() method that gets called when the server is stopped but when I put fw.close(); It says fw cannot be resolved. Please help!
The relevant section of the code is
public class MAIN extends JavaPlugin{{
try {
FileWriter fw = new FileWriter("plugins/TestMessage/messages.txt", true);
} catch (IOException e) {
e.printStackTrace();}
}
public void onEnable(){
Logger.getLogger("Minecraft").info("MessageBroadcaster made by cheeseballs500 aka weakwizardsucks2");
}
public void onDisable(){
fw.close();//fw cannot be resolved
}
EDIT: Fixed :D

Try creating the FileWriter outside of any methods, then setting it to something in your onEnable()... Here's an example:
public class Main extends JavaPlugin{{
FileWriter fw;//create the variable
#Override
public void onEnable(){
try{
fw = new FileWriter(this.getDataFolder() + "/messages.txt", true); //assign the variable to a value, and put the file in your plugin's folder
}
catch(IOException e){
e.printStackTrace();
}
}
#Override
public void onDisable(){
try{ //try-catch just incase
fw.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}

Try this..
public class MAIN extends JavaPlugin{
public MAIN() {
try {
this.fw = new FileWriter("plugins/TestMessage/messages.txt", true);
} catch (Exception e) {
// TODO: handle exception
}
}
FileWriter fw = null;
public void onEnable(){
Logger.getLogger("Minecraft").info("MessageBroadcaster made by cheeseballs500 aka weakwizardsucks2");
}
public void onDisable(){
try {
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}//fw cannot be resolved
}
}

Related

try catch vs try-with-resources

Why in the readFile2() I need to catch the FileNotFoundException and later the IOException that is thrown by the close() method, and in the try-with-resources(inside readfile1) Java doesn't ask me to handle the FileNotFoundException, what happened?
public class TryWithResourcesTest {
public static void main(String[] args) {
}
public static void readFile1() {
try(Reader reader = new BufferedReader(new FileReader("text.txt"))) {
} catch (IOException e) {
e.printStackTrace();
}
}
public static void readFile2() {
Reader reader = null;
try {
reader = new BufferedReader(new FileReader("text.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
if(reader != null)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
FileNotFoundException is a subclass of IOException. By catching the latter, you're catching the former too. It has nothing to do with try-catch vs. try-with-resources.

Logging into a text file in Android

I need to log my messages not only into system logs ( as I know, system log buffer is quite short, but I need to see logs for 3-5 days ), but also in a separate text file. Logging must be asynchronous.
Could you give me an advice about which component should I use in this case?
Thanks.
I hope it will be useful for you.
public void appendLog(String text) {
File logFile = new File("sdcard/log.file");
if (!logFile.exists()) {
try {
logFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(text);
buf.newLine();
buf.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Don't forget to add permission for android.permission.WRITE_EXTERNAL_STORAGE in Manifest!
Works asynchronously and dose not need to permission !
just remember call the init method from your application in onCreateMethod for initializing the Logger
class Logger {
private static File logFileLoc;
private static ExecutorService logExecutor;
public static void init(Context applicationContext, String logFileName, boolean reCreate) {
logFileLoc = new File(applicationContext.getCacheDir(), logFileName);
if (reCreate && logFileLoc.exists()) logFileLoc.delete();
logExecutor = Executors.newSingleThreadExecutor();
}
public static void log(final String tag, final String msg) {
if (logFileLoc == null) try {
throw new Exception("First you should call init method in your application");
} catch (Exception e) {
e.printStackTrace();
}
Log.d(tag, msg);
logExecutor.execute(new Runnable() {
#Override
public void run() {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(logFileLoc,true));
String timeStamp = DateFormat.getDateTimeInstance().format(new Date(System.currentTimeMillis()));
writer.append(timeStamp + " " + tag + " : " + msg );
writer.newLine();
writer.flush();
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
also you can do the same thing with Timber library for more info :
https://medium.com/#vicky7230/file-logging-with-timber-4e63a1b86a66

Repeatedly Writing to a File

I'm a moderately-experienced C++ guy slowly learning Java. I'm writing a program which needs to do the following:
Create a simple text file, default directory is fine
As the program runs, periodically write one line of data to the file. Depending on a number of factors, the program may write to the file once or a million times. There is no way of knowing which write will be the last.
I've been researching different ways to do this, and this is the working code I've come up with. There are two files, "PeteProgram.java" and "PeteFileMgr.java" :
/*
"PeteProgram.java"
*/
import java.io.*;
import java.lang.String;
public class PeteProgram {
public static void main(String[] args) throws IOException {
String PeteFilename="MyRecordsFile.txt";
Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(PeteFilename), "utf-8"));
PeteFileMgr MyPeteFileMgr = new PeteFileMgr(writer);
MyPeteFileMgr.AddThisString(writer, "Add this line #1\n");
MyPeteFileMgr.AddThisString(writer, "Add this line #2\n");
MyPeteFileMgr.AddThisString(writer, "Add this line #3\n");
}
}
//=====================================================================================================
//=====================================================================================================
/*
"PeteFileMgr.java"
*/
import java.io.*;
public class PeteFileMgr {
public PeteFileMgr(Writer writer) {
try {
writer.write("File created!");
} catch (IOException ex) {
// report
} finally {
try {writer.close();} catch (Exception ex) {}
}
}
void AddThisString(Writer writer, String AddThis) {
try {
writer.append(AddThis);
} catch (IOException ex) {
// report
} finally {
try {writer.close();} catch (Exception ex) {}
}
}
}
The initial creation of the file works just fine. However, the to-be-added lines are not written into the file. Because the program compiles and runs with no errors, I assume the program tries to write the added lines, fails, and throws an exception. (Unfortunately, I am working with a primitive compiler/debugger and can't see if this is the case.)
Does anyone spot my mistake?
Many thanks!
-P
That's because you're not flushing the Writer. You should call flush from time to time. Also, you should close your Writer at the end of your app, not after writing content into it. close method automatically flushes the contents of the writer.
So, this is how your code should look like:
public class PeteProgram {
public static void main(String[] args) {
String peteFilename = "MyRecordsFile.txt";
//here's when the physical file is created
Writer writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(peteFilename), "utf-8"));
PeteFileMgr peteFileMgr = new PeteFileMgr(writer);
peteFileMgr.addThisString(writer, "Add this line #1\n");
peteFileMgr.addThisString(writer, "Add this line #2\n");
peteFileMgr.addThisString(writer, "Add this line #3\n");
} catch (IOException e) {
//handle the exception
//basic handling
e.printStacktrace();
} finally {
//this is a must!
try { writer.close(); } catch(IOException silent) { }
}
}
}
public class PeteFileMgr {
public PeteFileMgr(Writer writer) {
try {
//this method is not creating the physical file
writer.write("File created!");
} catch (IOException ex) {
// report
} finally {
//remove this call to close
//try {writer.close();} catch (Exception ex) {}
}
}
public void addThisString(Writer writer, String addThis) {
try {
writer.append(addThis);
} catch (IOException ex) {
// report
} finally {
//remove this call to close
//try {writer.close();} catch (Exception ex) {}
}
}
}
Or if using Java 7 or superior using the try-with-resources:
public class PeteProgram {
public static void main(String[] args) {
String peteFilename = "MyRecordsFile.txt";
//here's when the physical file is created
try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(peteFilename), "utf-8"))) {
PeteFileMgr peteFileMgr = new PeteFileMgr(writer);
peteFileMgr.addThisString(writer, "Add this line #1\n");
peteFileMgr.addThisString(writer, "Add this line #2\n");
peteFileMgr.addThisString(writer, "Add this line #3\n");
} catch (IOException e) {
//handle the exception
//basic handling
e.printStacktrace();
}
}
}

Output text to a file with a class method java

I have a valet class method that should write an hourly wage to a file:
public void hourlyOverall() throws FileNotFoundException
{
PrintWriter out = new PrintWriter("wage info");
new FileOutputStream("wage info", true);
hourlyOverall = tips / hours + hourlyWage;
out.println(hourlyOverall);
}
However, when I run valet.hourlyOverall() in my main method, the file "wage info" is created but nothing is written to it. What am I doing wrong?
First of all use try-catch for Exception handling and then in the finally block close the OutputStream
out.flush();
Somthing like this
try {
PrintWriter out = new PrintWriter("wage info");
hourlyOverall=tips/hours+hourlyWage;
out.println(hourlyOverall);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
finally {
out.flush();
}
I think this is another way to solve your problem, but using another classes
public class valet {
public static void main(String []args)throws IOException
{
try
{
hourlyOverall()
}
catch(IOException ex)
{
System.out.println(ex+"\n");
}
}
public void hourlyOverall() throws IOException
{
FileWriter out = new FileWriter("wage info");
hourlyOverall=tips/hours+hourlyWage;
out.write(hourlyOverall+"\r\n");
out.close();
}
}
You probably shouldn't declare an anonymous FileOutputStream and you should probably close your PrintWriter,
PrintWriter out=new PrintWriter("wage info");
// new FileOutputStream("wage info",true);
hourlyOverall=tips/hours+hourlyWage;
out.println(hourlyOverall);
out.close(); // <-- like that
Do something like this (if java7 or above) :
public void hourlyOverall()
{
try (PrintWriter out=new PrintWriter("wage info")){
//new FileOutputStream("wage info",true);
hourlyOverall=tips/hours+hourlyWage;
out.println(hourlyOverall);
}catch (FileNotFoundException e) {
e.printStackTrace();
}
}
http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

java PrintWriter cannot be resolved

I have no idea why I get the message "cannot be resolved" on out in eclipse on the 11th line
import java.io.*;
public class driver {
public static void main(String[] args) {
try {
PrintWriter out = new PrintWriter("output.txt");
}
catch (FileNotFoundException e) {
System.out.print("file not found");
e.printStackTrace();
}
out.print("hello");
out.close();
}
}
OK so now I have this
import java.io.*;
public class driver {
public static void main(String[] args) {
PrintWriter out = null;
try {
out = new PrintWriter("output.txt");
}
catch (FileNotFoundException e) {
System.out.print("file not found");
e.printStackTrace();
}
out.print("hello");
out.close();
}
}
Why doesn't eclipse create a file once I close out?
Declare your PrintWriter before the try block so it's scope isn't limited to the try block.
You can also use new try-with-resource block introduced in JDK 1.7, in this advantage is you don't need to worry about closing any resource which implements Closable Interface.
Then code will look like this:
try (PrintWriter out = new PrintWriter("output.txt"))
{
out.print("hello");
}
catch (FileNotFoundException e)
{
System.out.print("file not found");
e.printStackTrace();
}

Categories