I am reading a txt file into a String buffer and writing the content into a word document using OutputStreamWriter.
The problem is that the formatting is not retained in the document. The spaces and the line breaks are not retained as in the text file. The txt file is formatted properly with spaces, page breaks, and tabs. I want to replicate the txt in word document. Please suggest how can the same formatting be retained. The link to the file is: http://s000.tinyupload.com/index.php?file_id=09876662859146558533.
This is the sample code:
private static String readTextFile() {
BufferedReader br = null;
String content = null;
try {
br = new BufferedReader(new FileReader("ORDER_INVOICE.TXT"));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
sb.append(System.lineSeparator());
}
content = sb.toString();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return content;
}
private static void createDocument(String docName, String content) {
FileOutputStream fout = null;
try {
fout = new FileOutputStream(docName);
OutputStreamWriter out = new OutputStreamWriter(fout);
out.write(content);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Try to change your readTextFile() like this and try.
BufferedReader br = null;
String content = null;
try {
br = new BufferedReader(new FileReader("ORDER_INVOICE.TXT"));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while(line != null) {
content += line + "\n";
line = br.readLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return content;
Actually if your using java 7, you can use try-with-resources in order to decrease the number of lines in your code.
Try to avoid printing \n chars. Use \r\n for Windows - remember that line separators differ across platforms.
A more reliable way is to use PrintWriter, see
How to write new line in Java FileOutputStream
After the discussion in comments:
the source file has unix line breaks
the output file is expected to have Windows line breaks
we shall strip the 0x0c (form feed - i.e. move to next page on the printer) from the source file, as it is non-printable.
public static void main(String[] args) throws IOException {
String content = new String(Files.readAllBytes(Paths.get("f:\\order_invoice.txt")))
.replace("\u000c","");
PrintWriter printWriter=new PrintWriter(new FileWriter("f:\\new_order_invoice.txt"));
for (String line:content.split("\\n")) {
printWriter.println(line);
}
printWriter.close();
}
So:
read the file as it is into a String
get rid of the form feed (0x0c, unicode u000c)
split the string at unix line breaks \n
write it out line by line using PrintWriter which uses the platform default line ending, i.e. windows cr-lf.
Remember that you can actually do this in one line, using a regexp to replace unix line endings to windows line endings in the string representing the whole file, and use Files.write to write out the whole file in one line. However this presented solution is probably a bit better as it always uses platform native line separators.
Related
I'm looking to create a find and replace java application which prompts users to call to a text file, print it out to a new file, ask user for a search word or phrase and a word to replace that searched word with. Here is the code I have so far. I can read the contents from the first file just fine but cannot write the contents from the first file to another. This is all done within a GUI code below
String loc = jTextField1.getText(); //gets location of initial file or "source"
String file = jTextField4.getText(); //new file path
String find = jTextField2.getText(); //find word inputted by user
String word = jTextField3.getText(); //replace "find" with word inputted by user
String line = null;
try {
BufferedReader br = new BufferedReader(new FileReader(loc));
while ((line = br.readLine()) !=null)
} catch (FileNotFoundException ex) {
Logger.getLogger(Assign6GUI.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Assign6GUI.class.getName()).log(Level.SEVERE, null, ex);
}
To write content to a file you need to use BufferedWriter
public static void writetoFile(String str, String FILE_PATH, String FILENAME ) {
BufferedWriter writer = null;
try {
File file = new File(FILE_PATH);
// if file doesnt exists, then create it
if (!file.exists()) {
file.mkdir();
}
file = new File(FILE_PATH + FILENAME);
file.createNewFile();
writer = new BufferedWriter(new FileWriter(file));
writer.write(str);
} catch (IOException e) {
LOGGER.debug(e);
} finally {
try {
if (writer != null) {
writer.close();
}
} catch (Exception e) {
LOGGER.debug(e);
}
}
}
to replace words in a string you should use the replace function in java
String str = someString.replace("OldText", "NewText");
I try to read file to string, I've try to make the encode to UTF-8 but still fail, it's return some weird characters in the output.
Here is my function to read file:
private static String readFile(String path, boolean isRaw) throws UnsupportedEncodingException, FileNotFoundException{
File fileDir = new File(path);
try{
BufferedReader in = new BufferedReader(
new InputStreamReader(
new FileInputStream(fileDir), "UTF-8"));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.close();
return str;
}
catch (UnsupportedEncodingException e)
{
System.out.println(e.getMessage());
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
return null;
}
The output of first line is: ��1
Here is my testing file https://www.dropbox.com/s/2linqmdoni77e5b/How.to.Get.Away.with.Murder.S01E01.720p.HDTV.X264-DIMENSION.srt?dl=0
Thanks in advance.
This file is encoded in UTF16-LE and has the Byte order mark which helps to determine the encoding. Use "UTF-16LE" charset (or StandardCharsets.UTF_16LE) and skip the first character of the file (for example, calling str.substring(1) on the first line).
It looks like your file is encoded as a BOM file. If you don't need to handle the BOM character, then open notepad++ and encode your file as UTF-8 without BOM
To handle a BOM file in java, take a look at this apache site for BOMInputStream
Example:
private static String readFile(String path, boolean isRaw) throws UnsupportedEncodingException, FileNotFoundException{
File fileDir = new File(path);
try{
BOMInputStream bomIn = new BOMInputStream(new FileInputStream(fileDir), ByteOrderMark.UTF_16LE);
//You can also detect UTF-8, UTF-16BE, UTF-32LE, UTF-32BE by using this below constructure
//BOMInputStream bomIn = new BOMInputStream(new FileInputStream(fileDir), ByteOrderMark.UTF_16LE,
// ByteOrderMark.UTF_16BE, ByteOrderMark.UTF_32LE, ByteOrderMark.UTF_32BE, ByteOrderMark.UTF_8);
if(bomIn.hasBOM()){
System.out.println("Input file was encoded as a bom file, the bom character has been removed");
}
BufferedReader in = new BufferedReader(
new InputStreamReader(
bomIn, "UTF-8"));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.close();
return str;
}
catch (UnsupportedEncodingException e)
{
System.out.println(e.getMessage());
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
return null;
}
If I have a String that contains some words with here and there a \n in between,
is there a way to write them into a .txt file on separate lines? For example:
File myFile = new File("TextFile.txt");
FileWriter fw = null;
try {
fw = new FileWriter(myFile.getAbsoluteFile());
} catch (IOException e) {
e.printStackTrace();
}
BufferedWriter bw = new BufferedWriter(fw);
try {
bw.write(myString);
} catch (IOException e) {
e.printStackTrace();
}
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
Where myString is something like:
"\nwords\nwords\nwords\n"
With this code I get in the text file words words words instead of
words
words
words
You can either use an editor which understands \n as newline, or use this code:
text = text.replaceAll("\n","\r\n");
I have few text files. Each text file contains some path and/or the reference of some other file.
File1
#file#>D:/FilePath/File2.txt
Mod1>/home/admin1/mod1
Mod2>/home/admin1/mod2
File2
Mod3>/home/admin1/mod3
Mod4>/home/admin1/mod4
All I want is, copy all the paths Mod1, Mod2, Mod3, Mod4 in another text file by supplying only File1.txt as input to my java program.
What I have done till now?
public void readTextFile(String fileName){
try {
br = new BufferedReader(new FileReader(new File(fileName)));
String line = br.readLine();
while(line!=null){
if(line.startsWith("#file#>")){
String string[] = line.split(">");
readTextFile(string[1]);
}
else if(line.contains(">")){
String string[] = line.split(">");
svnLinks.put(string[0], string[1]);
}
line=br.readLine();
}
} catch (Exception e) {
e.printStackTrace();
}
}
Currently my code reads the contents of File2.txt only, control does not come back to File1.txt.
Please ask if more inputs are required.
First of all you are jumping to another file without closing the current reader and when you come back you lose the cursor. Read one file first and then write all its contents that match to another file. Close the current reader (Don't close the writer) and then open the next file to read and so on.
Seems pretty simple. You need to write your file once your svnLinks Map is populated, assuming your present code works (haven't seen anything too weird in it).
So, once the Map is populated, you could use something along the lines of:
File newFile = new File("myPath/myNewFile.txt");
// TODO check file can be written
// TODO check file exists or create
FileOutputStream fos = null;
OutputStreamWriter osw = null;
BufferedWriter bw = null;
try {
fos = new FileOutputStream(newFile);
osw = new OutputStreamWriter(fos);
bw = new BufferedWriter(osw);
for (String key: svnLinks.keySet()) {
bw.write(key.concat(" my separator ").concat(svnLinks.get(key)).concat("myNewLine"));
}
}
catch (Throwable t) {
// TODO handle more gracefully
t.printStackTrace();
if (bw != null) {
try {
bw.close();
}
catch (Throwable t) {
t.printStackTrace();
}
}
Here is an non-recursive implementation of your method :
public static void readTextFile(String fileName) throws IOException {
LinkedList<String> list = new LinkedList<String>();
list.add(fileName);
while (!list.isEmpty()) {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(new File(list.pop())));
String line;
while ((line = br.readLine()) != null) {
if (line.startsWith("#file#>")) {
String string[] = line.split(">");
list.add(string[1]);
} else if (line.contains(">")) {
String string[] = line.split(">");
svnLinks.put(string[0], string[1]);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
br.close();
}
}
}
Just used a LinkedList to maintain the order. I suggest you to add some counter if you to limit the reading of files to a certain number(depth). eg:
while (!list.isEmpty() && readCount < 10 )
This will eliminate the chance of running the code to infinity(in case of circular reference).
I am trying to write a new line to a text file in android.
Here is my code:
FileOutputStream fOut;
try {
String newline = "\r\n";
fOut = openFileOutput("cache.txt", MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write(data);
osw.write(newline);
osw.flush();
osw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I have tried \n, \r\n and I did also try to get the system property for a new line, neither of them work.
The data variable contains previously data from the same file.
String data = "";
try {
FileInputStream in = openFileInput("cache.txt");
StringBuffer inLine = new StringBuffer();
InputStreamReader isr = new InputStreamReader(in, "ISO8859-1");
BufferedReader inRd = new BufferedReader(isr,8 * 1024);
String text;
while ((text = inRd.readLine()) != null) {
inLine.append(text);
}
in.close();
data = inLine.toString();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I had the same problems, tried every trick in the book.
My problem: the newline's were written, but while reading they were removed:
while (readString != null) {
datax.append(readString);
readString = buffreader.readLine();
}
The file was read line by line and concatenated, so the newline's disappeared.
I did not look at the original file in Notepad or something because I didn't know where to look on my phone, and my logscreen used the code which removed the newline's :-(
So the simple soultion was to put it back while reading:
while (readString != null) {
datax.append(readString);
datax.append("\n");
readString = buffreader.readLine();
}
I executed a similar program and it worked for me. I observed a strange behavior though. It added those new lines to the file, however the cursor remained at the first line. If you want to verify, write a String after your newline characters, you will see that the String is written just below those new lines.
I was having the same problem and was unable to write a newline. Instead I use BufferdWritter to write a new line into the file and it works for me.
Here is a sample code sniplet:
OutputStreamWriter out = new OutputStreamWriter(openFileOutput("cache.txt",0));
BufferedWriter bwriter = new BufferedWriter(out);
// write the contents to the file
bwriter.write("Input String"); //Enter the string here
bwriter.newLine();