• Post Reply Bookmark Topic Watch Topic
  • New Topic

Keeping formatting within a text file in Java?  RSS feed

 
Aarden Axford
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello! Just a quick question about the formatting of text files when using Java. I created a text file called Discount Fly that keeps track of things like a person's name, address, etc. Here is roughly what it looked like in the .txt file:
Name Address Postal Code
Jane Doe Anywhere St, 123 1A2 B3C

However, when I run this code:


It prints out into JOptionPane as:
NameAddressPostalCode
JaneDoe Anywhere St, 123 1A2 B3C

Is there anyway to maintain the formatting in JOptionPane? Also, I am new to writing programs that read from text files, so if somethings up with my code (i.e. java conventions) please tell me.
Thank you very much for any help/tips! Useful links are always appreciated ~
 
Campbell Ritchie
Marshal
Posts: 56593
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Most people would prefer to use a Scanner on a plain text file.
What is the encoding of the text file and what is the default encoding? If you are on Windows® it is probably ISO-8859-1 for both, so that should sort itself out.
What is the character separating words as space in the text file?
 
Aarden Axford
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Most people would prefer to use a Scanner on a plain text file.


I am not sure how to do this. Any useful links? I want to make sure I learn this properly...

What is the character separating words as space in the text file?


It's a tab space. I tried appending a "\t", but with my current code it only appends to the END of the entire line, which is not useful for me.

Thanks for any help! I'm looking into using Scanner right now...
 
Campbell Ritchie
Marshal
Posts: 56593
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What's a tab space? Is it same as a horizontal tab (=(char)0x09) which you can get with the key at the left with “tab” written on?
You can wrap your file reader in a Scanner but the simplest way to do it is probably like this:-The try (...) bit is called try with resources which you can read about in the Java® Tutorials.

Have you come across the replaceAll method of the String class? Beware: its first parameter is called regex so you need to pass a redular expression. I think the regular expression for the horizontal tab character is "\\t" but I am not certain.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!