I used a function where logger and parameters are initialized.
Although I called this function LogMsg and newline in console, but it gives one single line in the text file. Why is that so?
String logmsg="Line1\n"+"Line2\n";
public static void LogMsg(Logger logger,String pathname,Level level,String logmsg){
//logger=Logger.getLogger("LogMsg");
FileHandler fh=null;
try {
fh = new FileHandler(pathname,300000,1,true);
fh.setFormatter(new SimpleFormatter());
LogRecord record1 = new LogRecord(level, logmsg);
logger.addHandler(fh);
logger.log(record1);
fh.close();
} catch (SecurityException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
System.out.println("Failed to log message due to lack of permissions.");
} catch (IOException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
System.out.println("Failed to log message");
}
}
Try
String logmsg="Line1\r\n"+"Line2\r\n";
or better still
logmsg = String.Concat("Line1",Environment.NewLine,"Line2",Environment.NewLine);
Or better still use a StringBuilder somethimng like
logmsg = CreateLogMessage(new string [] {"Line1", "Line2"});
public static CreateLogMessage(string[] argLines);
{
StringBuilder sb = new StringBuilder(argLines.Length);
foreach(String line in argLines)
{
sb.AppendLine(line);
}
return sb.ToString();
}
Environment.Newline will deal with os differences in terms of which end of line token is expected.
Related
I have created a java gui which takes values from the user send it to python file for processing and then displays the output from the python file onto the java gui. This is working perfectly on eclipse but when i exported it into a jar file the output is not displayed. I've seen a bunch of other questions like this but they do not give a solution that would help me.
This is how i connect my python script to java.
public void connection(String name)
{
ProcessBuilder pb= new ProcessBuilder("python","recomold.py","--movie_name",name);
///System.out.println("running file");
Process process = null;
try {
process = pb.start();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
int err = 0;
try {
err = process.waitFor();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// System.out.println("any errors?"+(err==0 ? "no" : "yes"));
/* try {
System.out.println("python output "+ output(process.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
try {
matches.setText(output(process.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private String output(InputStream inputStream) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader br = null;
try{
br= new BufferedReader(new InputStreamReader(inputStream));
String line = null;
while((line=br.readLine())!=null)
{
sb.append(line+"\n");
//descp.setText("<html><br/><html>");
//sb.append("\n");
}
}
finally
{
br.close();
}
return sb.toString();
}
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
I am new (and German so my English is not the best :D)
I am working at a program, but I need to insert a BufferedReader & FileReader.
I am working with GUI(graphical user interface) , and I know the mistake that I have to insert a throws IOException but I honestly do not know at which position. (because it is everywhere right next to public static void main(String[] args) but this does not exist in GUI)
FileReader fr = new FileReader("pi.txt");
BufferedReader br = new BufferedReader(fr);
String zeile1 = br.readLine();
char[] c = zeile1.toCharArray();
System.out.println(c[2]);
Can somebody help me?
I have never used GUI, but you can catch it with try-catch:
try{
// your code
} catch (Exception e){
}
As suggested in comment, the best way is to catch specific exception and not the generic one.
In your case, You need:
FileReader fr;
try {
fr = new FileReader("pi.txt");
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//and
try {
String zeile1 = br.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
or
try {
// your code
} catch (FileNotFoundException e1) {
// log
} catch (IOException e) {
// log
}
I have a method that allows me to type part of the computer name into a jtextfield and I submit via jbutton. The cmd prompt successfully gives me the full computer name. So if I typed 111255 the command prompt will output coud111255. Query I'm using (#dsquery computer -name *%1)
This part works great. My issue is pulling the full computer name out of the batch file and assigning it to a java variable. I'm trying to append the full computer name to textArea, but it is only pulling the hardcoded value from here:
String dn = "CN=FDCD111304,OU=Workstations,OU=SIM,OU=Accounts,DC=FL,DC=NET";)
Any Suggestions on how to get the full computer name appended to textArea?
sendParam() passes half of computer name into batch script to find full computer name.
public static void sendParam(){
try{
String val = MISControlPanel.textField.getText(); //Put whatever you want to pass as a prefix in place of "Computer"
jLabel1.setText(val);
Process p ;
p = Runtime.getRuntime().exec("cmd /c start c:\\computerQuery.bat "+val+"");
}
catch(Exception e){
e.printStackTrace();
}
}
StringBuffer sbuffer = new StringBuffer();
BufferedReader in = new BufferedReader(new InputStreamReader(p
.getInputStream()));
try {
while ((line = in.readLine()) != null) {
System.out.println(line);
//textArea.append(line);
String dn = "CN=FDCD111304,OU=Workstations,OU=SIM,OU=Accounts,DC=FL,DC=NET";
LdapName ldapName = new LdapName(dn);
String commonName = (String) ldapName.getRdn(ldapName.size() - 1).getValue();
textArea.append(String.format(" %s%n", commonName));
//textArea.setText(ComputerQuery.val);
selectedComputerFromAD.setText(commonName);
selectedComputerFromAD.setFont(new Font("Tahoma", Font.BOLD, 14));
selectedComputerFromAD.setForeground(Color.RED);
selectedComputerFromAD.setBounds(349, 84, 102, 19);
frame.getContentPane().add(selectedComputerFromAD);
}
ComputerQuery.sendParam();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InvalidNameException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally
{
try {
fw.close();
}
catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
try {
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
ComputerQuery.sendParam();
}
});
I'm taking a course in Java, and the assignment is to write a calendar program that can write and retrieve events from a file.
My problem is that I'm only getting the first value of my written array. returned from the "input.readObject"
Here is my getFile method calling looking to read the file.
static String[] Entry = new String [35];
public static void getFile(Object month, String year) throws IOException
{
ObjectInputStream input = new ObjectInputStream(new FileInputStream(month+year+".txt"));
try
{
String[] LoadedEntry = (String[])(input.readObject());
Entry = (String[]) LoadedEntry;
}
catch (IOException e)
{
// TODO Auto-generated catch block
//e.printStackTrace();
System.out.println("File not found, creating new file...");
}
catch (ClassNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
input.close();
}
}
And the method that calls it, and writes the desired code after the getFile method executes.
public static void saveEvent(String month, int day, String year, String calendarEvent)
{
String[] EntryF = new String[35];
String[] Sample = {"1", "2", "3", "4", "5"};
try
{
getFile(month, year);
System.out.println("Past getFile");
EntryF = Entry;
//EntryF = Sample;
EntryF[day] = calendarEvent;
ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(month + year+".txt", true));
output.writeObject(EntryF);
output.reset();
output.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
Been racking my brain for all day, and cannot get this thing to work... Does anyone see where I went wrong?
I can verify that the object is being saved and passed down into the saveEvent method because the written textfile is changing, but it's just not reading in the full contents of the file correctly..
Thanks,
Andy
You will need a loop to read rest of the stream. So far you are reading just the first part of the stream, so the following will have to be in a loop:
String[] loadedEntry = (String[])(input.readObject());
And you will also need to determine a signal to use to end the loop.
For e.g. using input.read() will result in -1 when the end of stream is reached.
You can read the entire file with something like the following:
try {
while (Terminating_Condition) {
String[] loadedEntry = (String[]) (input.readObject());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Hope that helps.