Reading a text file

B

bruce

I am reading a file with

BufferedReader reader = null;
StringBuffer contents = new StringBuffer();
while ((text = reader.readLine()) != null) {
contents.append(text)
.append(System.getProperty(
"line.separator"));
}

This code reads the file fine. My problem is that when I put the data
into a text, it is displayed with a space character before ever
character. (bruce => b r u c e)

What am I doing wrong??

Thanks...

Bruce
 
E

Eric Sosman

I am reading a file with

BufferedReader reader = null;
StringBuffer contents = new StringBuffer();
while ((text = reader.readLine()) != null) {
contents.append(text)
.append(System.getProperty(
"line.separator"));
}

This code reads the file fine. My problem is that when I put the data
into a text, it is displayed with a space character before ever
character. (bruce => b r u c e)

What am I doing wrong??

Something in the "it is displayed" code would be my guess.
 
B

bruce

     Something in the "it is displayed" code would be my guess.

This is how I am displaying the input text:

txtText.setText(contents.toString());

Is that the wrong way to insert the file data (contents) into the text
area (txtText)?

Thanks for the response...

Bruce
 
E

Eric Sosman

This is how I am displaying the input text:

txtText.setText(contents.toString());

Is that the wrong way to insert the file data (contents) into the text
area (txtText)?

Sorry: I can't get your code to compile, much less run and
exhibit desirable or undesirable behavior.

(In other words, STOP dripping your code out line by line by
incomplete out-of-context line! "Doctor, it hurts!" "What hurts?"
"Even worse than yesterday!" Please provide code that is SHORT and
SELF-CONTAINED and COMPLETE and COMPILABLE. Yes, including the
package and imports and class lines: Something someone who feels like
being helpful can dump AS IS through his Java compiler and see what
happens. I can't debug what I can't see. Stop teasing!)
 
B

bruce

     Sorry: I can't get your code to compile, much less run and
exhibit desirable or undesirable behavior.

     (In other words, STOP dripping your code out line by line by
incomplete out-of-context line!  "Doctor, it hurts!"  "What hurts?"
"Even worse than yesterday!"  Please provide code that is SHORT and
SELF-CONTAINED and COMPLETE and COMPILABLE.  Yes, including the
package and imports and class lines: Something someone who feels like
being helpful can dump AS IS through his Java compiler and see what
happens.  I can't debug what I can't see.  Stop teasing!)

I am sorry but including all the code is hard to do. I am using
NetBeans and it generates a lot of support code.

I don't now if you can compile it or not. This program is a test
program to teach me how to use the JFileChooser.

I know you're trying to help and I do appreciate it.. This is the best
I can do. It does include the NetBeans generated code.

package VitalRecords;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JFrame;

/**
*
* @author Bruce
*/
public class VitalRecords extends JFrame {

JFileChooser fc;
BufferedReader reader = null;
StringBuffer contents = new StringBuffer();

/** Creates new form VitalRecords */
public VitalRecords() {
initComponents();
fc = new JFileChooser();
}

/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

jScrollPane1 = new javax.swing.JScrollPane();
txtText = new javax.swing.JTextArea();
lblFileName = new javax.swing.JLabel();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
mnuOpenFile = new javax.swing.JMenuItem();
jMenu2 = new javax.swing.JMenu();


setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

txtText.setColumns(20);
txtText.setRows(5);
jScrollPane1.setViewportView(txtText);

lblFileName.setText("File Name: ");

jMenu1.setText("File");

mnuOpenFile.setText("Open File");
mnuOpenFile.addActionListener(new
java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent
evt) {
mnuOpenFileActionPerformed(evt);
}
});
jMenu1.add(mnuOpenFile);

jMenuBar1.add(jMenu1);

jMenu2.setText("Edit");
jMenuBar1.add(jMenu2);

setJMenuBar(jMenuBar1);

javax.swing.GroupLayout layout = new
javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1,
javax.swing.GroupLayout.DEFAULT_SIZE, 703, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(lblFileName)
.addContainerGap(625, Short.MAX_VALUE))
);
layout.setVerticalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(13, 13, 13)
.addComponent(lblFileName)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement..UNRELATED)
.addComponent(jScrollPane1,
javax.swing.GroupLayout.DEFAULT_SIZE, 357, Short.MAX_VALUE))
);

pack();
}// </editor-fold>

private void mnuOpenFileActionPerformed(java.awt.event.ActionEvent
evt) {
int returnVal = fc.showOpenDialog(VitalRecords.this);
System.out.println(returnVal);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
String fileLabel = lblFileName.getText();
String fileName = fc.getName(file);
lblFileName.setText(fileLabel + fileName);
try {

reader = new BufferedReader(new FileReader(file));
} catch (FileNotFoundException ex) {

Logger.getLogger(VitalRecords.class.getName()).log(Level.SEVERE, null,
ex);
}
String text = null;


try {
while ((text = reader.readLine()) != null) {
contents.append(text)
.append(System.getProperty(
"line.separator"));
}
} catch (IOException ex) {

Logger.getLogger(VitalRecords.class.getName()).log(Level.SEVERE, null,
ex);
}
txtText.setText(contents.toString());
System.out.println(contents.toString());

}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new VitalRecords().setVisible(true);
}
});
}

// Variables declaration - do not modify
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel lblFileName;
private javax.swing.JMenuItem mnuOpenFile;
private javax.swing.JTextArea txtText;
// End of variables declaration

}
 
E

Eric Sosman

[...] Please provide code that is SHORT and
SELF-CONTAINED and COMPLETE and COMPILABLE. [...]

I am sorry but including all the code is hard to do. I am using
NetBeans and it generates a lot of support code. [...]

Fine -- But to demonstrate the problem, do you really need the
Logger stuff, or the Menu handling, or three-quarters of the rest
of the code? No: All you need is the JFrame, the JTextArea, and
the read-file-and-insert code. Well, all right, maybe the JScrollPane
too -- but much of what you provided was purely irrelevant to the
problem at hand.

Still, I did what I could. I compiled it under NetBeans (and
it compiled on the first try; thanks for the effort), and I ran it
(and it ran; ditto), and I fed it a handy text file -- and I don't
see the problem you describe. The content of the text file shows
up in the text area, looking just like the content that shows up in
System.out (except for the font, of course).

Since the problem isn't with the code ("It works fine for me"),
I suspect something's screwy with the input file you're choosing.
What's its provenance? Did it come from some other system, maybe
a system that favors different character encodings or something?
Have you examined it in a hex editor to see if there are any strange
bytes interspersed with those you expect? "When you have eliminated
the impossible, whatever remains, however improbable, must be the
truth" -- and I think we've shown that the code (although it could
use some improvement) is not the root of your problem. Hence, we
must follow Mr. Holmes' dictum and look elsewhere.
 
M

markspace

I don't now if you can compile it or not. This program is a test
program to teach me how to use the JFileChooser.


This seems to work fine for me. No extra spaces or anything. Are you
sure it reproduces the problem? What error should I be looking for?
 
B

bruce

I am reading a file with

    BufferedReader reader = null;
    StringBuffer contents = new StringBuffer();
    while ((text = reader.readLine()) != null) {
                contents.append(text)
                    .append(System.getProperty(
                        "line.separator"));
                }

This code reads the file fine.  My problem is that when I put the data
into a text, it is displayed with a space character before ever
character. (bruce => b r u c e)

What am I doing wrong??

Thanks...

Bruce

I have just learned something. I don't know what it is but it appears
that not all files give this space problem. I have loaded several
other .txt files with no problem. So, I have some more testing to do
before I can define the problem.

Thanks..

Bruce
 
B

bruce

This seems to work fine for me.  No extra spaces or anything.  Are you
sure it reproduces the problem?  What error should I be looking for?

I'm not getting any error. Yes, I was able to get it work with a
different .txt file. So I need to do some more testing to try and
understand the difference in the text files.

Thanks for the help...

Bruce
 
B

bruce

I have just learned something. I don't know what it is but it appears
that not all files give this space problem. I have loaded several
other .txt files with no problem. So, I have some more testing to do
before I can define the problem.

Thanks..

Bruce
 
B

bruce

I have just learned something. I don't know what it is but it appears
that not all files give this space problem. I have loaded several
other .txt files with no problem. So, I have some more testing to do
before I can define the problem.

Thanks..

Bruce

Okay.. I still don't know how the problem appeared. But, I loaded the
problem file into Notepad+, set the Encoding to UTF-8. The problem is
gone. So, somehow the problem file was saved with Encoding set to
something that gave the spacing problem.

Problem identified.

Thanks for all the help..

Bruce
 
J

Joshua Cranmer

Okay.. I still don't know how the problem appeared. But, I loaded the
problem file into Notepad+, set the Encoding to UTF-8. The problem is
gone. So, somehow the problem file was saved with Encoding set to
something that gave the spacing problem.

If it was set to Unicode in Notepad, it would have saved as a UTF-16
file, so the first characters would have been null characters. This was
something I had considered, but I am used to terminals simply ignoring
null characters on output, so I didn't know if the Swing stuff would
have displayed it as nothing or a space. Apparently, it is the latter...
 
B

bruce

[...] Please provide code that is SHORT and
SELF-CONTAINED and COMPLETE and COMPILABLE.  [...]
I am sorry but including all the code is hard to do. I am using
NetBeans and it generates a lot of support code. [...]

     Fine -- But to demonstrate the problem, do you really need the
Logger stuff, or the Menu handling, or three-quarters of the rest
of the code?  No: All you need is the JFrame, the JTextArea, and
the read-file-and-insert code.  Well, all right, maybe the JScrollPane
too -- but much of what you provided was purely irrelevant to the
problem at hand.

     Still, I did what I could.  I compiled it under NetBeans (and
it compiled on the first try; thanks for the effort), and I ran it
(and it ran; ditto), and I fed it a handy text file -- and I don't
see the problem you describe.  The content of the text file shows
up in the text area, looking just like the content that shows up in
System.out (except for the font, of course).

     Since the problem isn't with the code ("It works fine for me"),
I suspect something's screwy with the input file you're choosing.
What's its provenance?  Did it come from some other system, maybe
a system that favors different character encodings or something?
Have you examined it in a hex editor to see if there are any strange
bytes interspersed with those you expect?  "When you have eliminated
the impossible, whatever remains, however improbable, must be the
truth" -- and I think we've shown that the code (although it could
use some improvement) is not the root of your problem.  Hence, we
must follow Mr. Holmes' dictum and look elsewhere.

As you state, the problem was elsewhere, namely it was an encoding
problem. I've got a suspicion that it might have been an MS Word
document saved as a .txt file. I need to head for bed but I'll spend
ome time trying to identify the cause of the Encoding problem.

Thanks loads for helping...

Bruce
 
R

RedGrittyBrick

I am reading a file with

BufferedReader reader = null;
StringBuffer contents = new StringBuffer();
while ((text = reader.readLine()) != null) {
contents.append(text)
.append(System.getProperty(
"line.separator"));
}

This code reads the file fine. My problem is that when I put the data
into a text, it is displayed with a space character before ever
character. (bruce => b r u c e)

What am I doing wrong??

Some Microsoft programs, such as Notepad, will write text in UTF-16
encoding (which it calls "Unicode")

If you read that using Java code that is expecting UTF-8 or an 8-bit
encoding, you can get the effect you describe.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top