Printwriter println: no new line created - java

I am trying to decode an outlook .MSG file to a text file, using Apache POI classes.
Everything works fine, except for the println method of PrintWriter: it doesn´t create a new line.
It just concatenates every sentence directly one after another. The result of the code snippet below is
"De: textPara: " iso
"De: "
"Para: "
I tried the code on several machines: it works on my local tomcat instalation (Windows machine), but fails on a tomcat or Weblogic instalation on a Solaris platform. I thought it had something to do with the encoding algorithm, so I used PrintStream in stead of Printwriter, indicating the encoding ISO-8859-1, but no luck neither.
Any idea?
try {
byte [] msgByte = Base64.decodeBase64(msgBase64);
InputStream inputMsg = new ByteArrayInputStream(msgByte);
msg = new MAPIMessage(inputMsg);
/* 1. Transform MSG to TXT. */
try {
txtOut = new PrintWriter(outputMsg);
try {
String displayFrom = msg.getDisplayFrom();
txtOut.println("De: "+displayFrom);
} catch (ChunkNotFoundException e) {
_logger.info("Error extrayendo displayFrom: "+e);
}
try {
String displayTo = msg.getDisplayTo();
txtOut.println("Para: "+displayTo);
} catch (ChunkNotFoundException e) {
_logger.info("Error extrayendo displayTo: "+e);
}
} finally {
if(txtOut != null) {
txtOut.close();}
else {
_logger.error("No se ha podido parsear el mensaje.");
}
}

Change the following:
txtOut.print("De: "+displayFrom + "\r\n");
txtOut.print("Para: "+displayTo + "\r\n");
This is related to how PrintWriter.println() generates the Line break depending of the Operating System. For unix systems is LF (\n), for Windows is CR+LF (\r\n).
Notice how I added the "\r\n" which means CR+LF and used print() instead of println(). This way the line break generated is not platform dependent.
You can also add the following method to your class to avoid duplicity and just call this custom println() instead of directly calling txtOut.print().
private static final String LINE_SEPARATOR = "\r\n";
public void println(String str) {
txtOut.print(str + LINE_SEPARATOR);
}
This way you just call println() method.

Related

JMS TextMessage not recognizing CR LF

It appears to me like JMS TextMessage containing Java.lang.String isn't recognizing \r\n as line-break but instead treating the CR LF as part of input on a Windows machine.
#Override
public void onMessage(Message message) {
try {
String text = ((TextMessage)message).getText();
String line=null;
BufferedReader br = new BufferedReader(new StringReader(text));
for(line = br.readLine(); line != null; line = br.readLine()) {
System.out.println(line);
}
catch (JMSException e) {
System.err.println( "Error processing message: " + e.getMessage() );
e.printStackTrace();
}
Can anyone provide any input and /or recommednations around the same.
It's not completely clear from your question, but it sounds like the string is read correctly on input, but it is not being formatted correctly by the println output.
Control characters like line-feeds and and carriage returns are just like any other character in a string. What makes them different is how they are interpreted by the output device, lie a terminal program (e.g. linux terminal, putty, etc.) or the windows command prompt.
If you are printing this string to a destination that does not interpret these characters correctly, you may not see proper formatting even if the string data is correct. For example some IDE's output windows do not correctly format certain control characters, so you'll see different formatting in your IDE than you would see in an actual terminal.
One possible reason could be that it is not sent properly from the source system. I would look there to see what can be done next. Most languages offer cross-platform EOL constant's which might come in handy. For instance, Ruby has four:
irb(main):002:0> require 'English'; test = "One"+ $INPUT_RECORD_SEPARATOR
=> "One\n"
irb(main):003:0> test1 = "One" + $/
=> "One\n"
irb(main):004:0> test2 = "One"+$-0
=> "One\n"
irb(main):005:0> require 'English';test3="One"+$RS
=> "One\n"
irb(main):006:0>
You can try this:
String text = ((TextMessage)message).getText();
if(text!=null)
text=text.replaceAll("\r\n","");

Writing to a text file within a loop - JAVA

I've got a loop that reads through a text file and outputs it, now I'm trying to get it to loop through, and write what's printed out into a text file as I want it to display as HTML. This is what I've got so far for this method:
public void hChoice()
{
File fbScores = new File ("P:/SD/Assignment1/fbScores.txt");
String line = "";
try {
Scanner scanScores = new Scanner(fbScores);
while(scanScores.hasNext())
{
line = scanScores.nextLine();
stringArr = line.split(":");
if(stringArr.length == 4)
{
System.out.println("<h1>" + stringArr[0]+" [" +stringArr[2]+"] |" + stringArr[1]+" ["+ stringArr[3]+" ]<br></h1> ");
PrintWriter out = new PrintWriter("P:/SD/Assignment1/HTMLscores.txt");
out.close();
}
}
}
catch (FileNotFoundException e)
{
System.out.println("problem " +e.getMessage());
}
}
I've added the HTML tags in the print out and it prints it out fine, but I've tried several different methods to get it to print to a text file but none have worked. Pretty new to Java so any help would be much appreciated. Thankyou. :)
You've gotten your syntax and code wrong for writing to files.
Please Google and check the right syntax for writing to files using java. Plenty of resources available. You'll learn better if you try it yourself.
FYR, here is one: http://www.tutorialspoint.com/java/java_files_io.htm

Why this simple program leads to different carriage return/line feed file when executed in Java and AIX?

If I run this simple program on Windows 7 and then on AIX (Unix system) and compare the two generated files using a tool such as Winmerge or Compare It, it tells me that the Carriage Return and Line Feed are different but the content identical.
Why is that? Isn't supposed to be the same if both use the same encoding "UTF-8" in this case?
How can I make both files totally equal?
public class WriteFile {
public static void main(String[] args) throws IOException {
write();
}
public static void write() throws IOException {
File file = new File("/tmp/test.txt");
file.delete();
file.createNewFile();
String str = "hello";
FileOutputStream fileOs = new FileOutputStream(file);
PrintWriter writer = new PrintWriter(new OutputStreamWriter(fileOs, "UTF-8"), true);
writer.println(str);
writer.close();
}
}
Different operating systems use different newline conventions:
On Windows, newlines are CR+LF;
On Unix, newlines are LF.
(If you're curious, there's more.).
If you need the output files to be identical, don't use println(), but write \n or \r\n instead:
writer.printf("%s\n", str); // LF
writer.printf("%s\r\n", str); // CR+LF
Use
writer.print(str + "\n");
instead of
writer.println(str);
Like it's been said, you should switch from using println(String) to print(String) or printf(String, ...)
Check out the documentation for println(String) (emphasis mine):
Prints a String and then terminates the line. This method behaves as
though it invokes print(String) and then println().
And the docs for println():
Terminates the current line by writing the line separator string. The
line separator string is defined by the system property
line.separator, and is not necessarily a single newline character
('\n').
You can read about the line.separator system property here.
I would go with aix's suggestion of using
writer.printf("%s\n", str);

Runtime.exec on argument containing multiple spaces

How can I make the following run?
public class ExecTest {
public static void main(String[] args) {
try {
//Notice the multiple spaces in the argument
String[] cmd = {"explorer.exe", "/select,\"C:\\New Folder\\file.txt\""};
//btw this works
//String cmd = "explorer.exe /select,\"C:\\New Folder\\file.txt\"";
//and surprisingly this doesn't work
//String[] cmd = {"explorer.exe", "/select,\"C:\\New Folder\\file.txt\""};
//Update: and (as crazy as it seems) the following also worked
//String[] cmd = {"explorer.exe", "/select,\"C:\\New", "Folder\\file.txt\""};
Runtime.getRuntime().exec(cmd);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Using Java 6. Tested under Vista x64. By the way, taking the string that gets executed (you'll have to use the String version of exec to get it) and using it in the Search field of Vista's start menu will run as expected.
Ok, this is not simply an update but also an answer so I'm filing it as one. According to all information I could find, the following should theoretically do it:
String[] cmd = {"explorer.exe", "/select,\"C:\New", "", "", "", "", "", "", "Folder\file.txt\""};
The multiple spaces have been broken into empty strings and the array version of exec is used.
Using the above array, I debugged the loop in lines 50-75 of java.lang.ProcessImpl where a string is finally constructed. The resulting string was:
explorer.exe /select,"C:\New Folder\file.txt"
This is what is passed as the 1st argument to ProcessImpl's native create method (line 118 same class), which as it seems fails to run properly this command.
So I guess it all ends here... sadly.
Thnx prunge for pointing out the java bug.
Thnx everyone for their time and interest!
A miracle, it works!
Don't ask me why, but when i, after quite a while of nerve-wrecking research in the internets, was close to give up and use a temporary batch file as a workaround, i forgot to add the /select, parameter to the command, and, who would have thought, the following works on my Win 7 32Bit System.
String param = "\"C:\\Users\\ME\\AppData\\Local\\Microsoft\\Windows\\Temporary Internet Files\\\"";
try {
String[]commands = new String[]{"explorer.exe", param};
Process child = Runtime.getRuntime().exec(commands);
} catch (IOException e1) {
System.out.println("...");
}
General Solution:
The solution of the bug-database mentioned by prunge in his post (http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6511002) worked fine for me.
Reason:
Apparently the problem lies with the commenting of some characters done by java which it does before actually executing the command string.
You have to do the commenting yourself by tokenizing your command string, to prevent the faulty java one to spring into action and mess everything up.
How to fix:
So, in my case i had to do the following (tokenizing my command string, so that no spaces are left inside the string):
String param[] = {
"explorer.exe",
"/select,C:\\Users\\ME\\AppData\\Local\\Microsoft\\Windows\\Temporary",
"Internet",
"Files\\"};
try {
Process child = Runtime.getRuntime().exec(param);
} catch (IOException e1) {
System.out.println("...");
}
As you can see i basically started a new String wherever a space occured, so "Temporary Internet Files" became "Temporary","Internet","Files".
Always use Runtime.exec(String[]), not Runtime.exec(String) unless the command line is extremely simple.
Use new File(pathName).canExecute() first to check whether it's executable or not
EDIT:
public static void runAll(String... cmd)
{
for(String s : cmd)
{
try
{
Runtime.getRuntime().exec(cmd);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
and then you can use it like: runAll("explorer.exe", "taskmgr.exe");
The characters ,-& and double spaces, all combined are a nightmare!
All the answers exposed here failed for "\\NAS\media\Music\Artistes\E\Earth, Wind & Fire\1992 - The eternal dance - Vol. 1 (1971-1975) (double space between 'Vol. 1' and '(1971').
I have no other choice than writing a temporary batch file:
void openFolderOf( Album album ) {
try {
final String path = album._playList.getParent();
final File batch = File.createTempFile( getClass().getSimpleName(), ".bat" );
try( PrintStream ps = new PrintStream( batch )) {
ps.println( "explorer.exe \"" + path + '"' );
}
Runtime.getRuntime().exec( batch.getAbsolutePath());
}
catch( final Throwable t ) {
t.printStackTrace();
}
}
Note: on cmd.exe, the line explorer "\\NAS..." works well but not with Runtime.exec() nor ProcessBuilder.
Could be a Java bug. See:
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6511002
Did a bit of debugging out of curiosity, I think things are becoming unstuck in java.lang.ProcessImpl (see the constructor). Noticed that when it got to actually calling the underlying Windows API the string had turned into
explorer.exe "/select,"c:\New Folder\test.txt""
So that might explain why, as for workarounds see the bug database link.
For your specific case of needing the reveal/select command, I get around the windows quote nightmare by using cmd /c start:
String[] cmd = {"cmd", "/c", "start explorer.exe /select," + path};
Where path is the absolute path from a File object.
A better way to do it would be using ProcessBuilder object:
Process p;
p = new ProcessBuilder("/Applications/Sublime Text.app/Contents/MacOS/sublime_text", homeDir + _CURL_POST_PUT_CMDS).start();
int exitValue = p.waitFor();
if (exitValue != 0){
System.out.println("Error to open " + homeDir + _CURL_POST_PUT_CMDS);
}
Simple way to resolve this problem for files is java.awt.Desktop Since 1.6
Example:
Desktop.getDesktop().open(new File(fullFileName));

Executing a .sql file through Java

I have a sql script file, i need to execute commands present in that through java. I searched in internet regarding the same, i got some code defining parsers to split the SQL statements and executing that. But none of them worked for my sql script file.Because my script file contains both create statements and alter statements without semicolon at the end[Instead it has GO]Can anybody suggest a solution to execute the script file?
Thanks,
Mahesh
For simple scripts I generally use this class from ibatis - ScriptRunner. Alternative you can spawn a new db client process from Java and feed in the script you wan't execute. This will work for all scripts, as simple solutions like ScriptRunner don't work well when the delimiters in the sql files get changed for instance.
Here's an example how to feed the sql as a string to a spawed db client process:
private void runSql(String pSql) {
String tCommand = "mysql -u " + username + (password != null ? " -p" + password : "") + " " + dbName;
System.out.println(tCommand);
try {
Process tProcess = Runtime.getRuntime().exec(tCommand);
OutputStream tOutputStream = tProcess.getOutputStream();
Writer w = new OutputStreamWriter(tOutputStream);
System.out.println(pSql);
w.write(pSql);
w.flush();
Scanner in = new Scanner(tProcess.getErrorStream());
String errorMessage = "";
while (in.hasNext()) {
errorMessage += in.next() + " ";
}
if (errorMessage.length() > 0) {
System.out.println(errorMessage);
throw new ClientSqlExecutionException(errorMessage);
}
} catch (IOException e) {
e.printStackTrace();
}
}
Have a look at Mybatis Migrations code, it does something like the one you need:
http://code.google.com/p/mybatis/wiki/Migration
You need to change the parser so it produces executable statements. But I'm not sure I understand what you mean when you say "execute through Java".
Java won't execute those SQL statements - the database you connect to will. Java can connect to a database using JDBC and send the SQL statements from the file.
I don't see why you have to parse the SQL, unless you want Java to validate them before sending them on to the database server. The server will parse and validate them again, so it feels like you're doing extra work for nothing.
The simplest solution I can present to you is this, presuming I understand your question.
1) Read text file into a string or array via Java IO.
2) Pass string or array to MySQL via JDBC.
Read from file example,
import java.io.*;
class FileRead
{
public static void main(String args[])
{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
acquired from, http://www.roseindia.net/java/beginners/java-read-file-line-by-line.shtml
The simplest way is to simply get the statements and check if they need they semi-column at the end: (this is an example and only works if it is a statement by line:
public void executeScript(String script) {
BufferedReader in = new BufferedReader(new FileReader(script));
while (in.read() > 0) {
String statement = in.readLine();
statement = statement.trim().toLowerCase();
String command = statement.split("[ ]+")[0]; // split the statement.
if (command.equals("insert") || command.equals("update") /* || any other */) {
statement = statement + ";";
}
// execute statement using jdbc
}
}
If you do not know how to use jdbc, just ask :-)
Use this slightly modified version of the com.ibatis.common.jdbc.ScriptRunner class which is fully self contained, i.e. you do not need to have any third party jar dependencies.
It is possible to change the delimiter from ; to GO. I think that should do the trick.
Here is an example:
Reader reader = new BufferedReader(*** Your FileReader instance ***);
try
{
ScriptRunner runner = new ScriptRunner(connection, false, true);
runner.setDelimiter("GO", true);
runner.runScript(reader);
}
finally
{
reader.close();
}
Apache Ant SQL Task worked for me.
https://ant.apache.org/manual/Tasks/sql.html

Categories