Line separator for text files

Hello
I am writing a tab limited file which gets its data from a string[][] array . When i try opening the file its messed up with square blocks in notepad and looks great with wordpad. I do know that Unix has '\n' as the line separator, whereas windows has '\r\n' and mac has '\r'.
The problem is the file is created on unix system, but its opened on windows or mac systems. Does anyone has a suggestion how can i fix this. I did tried using 'line.separator' but that doesn't help..which is obvious since it uses the unix separator.
Please let me know if anyone can help
I am writing to the file using PrintWriter
thanx

isn't there a way just to know whats the line
separator used in the original file?The following will check out the line separator of a file..
final public class TestSeparator{
public static void main(String[] args) throws Exception{
java.io.BufferedReader br =null;
int k=0x0,temp=0x0;
try{
br =new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream("TestSeparator.java"),"UTF8"));//file and encoding are arbitrary
while((k=br.read())!=-1){
if((temp==(char)0xd)&&(k!=(char)0xa)) System.out.println();
if(k==(char)0xd||k==(char)0xa){
   if(k==(char)0xd) {
      System.out.print("r");
   if(k==(char)0xa) {
      System.out.print("n");
    if(temp==(char)0xd||k==(char)0xa) System.out.println();
    temp=k;
}//end of while
System.out.println("");
}finally{
     if(br!=null) br.close();
}

Similar Messages

  • How to add an space for every line in a text file in 46.B?

    Hi Friends!!
    My problem is the following,
    I need to add spaces in all lines of a text file
    Ej.'ABC ' , I'm using GUI_DOWNLOAD to download the internal table, but the function truncates all spaces, as it is 46B doesn't have the option for allowing the spaces at the end of each line,
    Do you know what can I do?? is there any other function module I could use?? I also tried with WS_DOWNLOAD but it didn't help!
    Thanks so much in advance!!!
    Frinee

    This a short example:
    data: begin of mytable occurs 0,
            line(2),
            lspace type x value '20',
            lenter type x value '0D0A',
          end of mytable.
    mytable-line = '1'.
    condense mytable-line.
    append mytable.
    mytable-line = '2'.
    condense mytable-line.
    append mytable.
    mytable-line = '3'.
    condense mytable-line.
    append mytable.
    call function 'GUI_DOWNLOAD'
         EXPORTING
           BIN_FILESIZE = 50
            FILENAME = 'C:\mybinfile.txt'
            FILETYPE = 'BIN'
         TABLES
            DATA_TAB = mytable
         EXCEPTIONS
           others = 9.

  • CLIENT_TEXT_IO : cannot insert new line into a text file

    Facts:
    Developer 10g
    AS 10g
    Web utility
    Problem:
    i am traying to
    Open a text file. using CLIENT_TEXT_IO.FOPEN
    insert a record in to a text file using CLIENT_TEXT_IO.PUTF
    insert a new line using chr(10) or CLIENT_TEXT_IO.NEW_LINE
    or CLIENT_TEXT_IO.put_line
    insert the next record
    Close the file.
    all work except insert a new line
    Why !!!
    it was Working fine in 6i, but now in 10g and Webutil is not working
    plz help

    Hi you can put a new line in a text file using System.getProperty("line.separator"). This implementation will work for every OS.
    import java.io.*;
    class Demo{
    public static void main(String args[]) throws Exception {
    FileWriter fr = new FileWriter("FileDemo.txt");
         fr.write("AAAAAAAAAA");
    fr.write(System.getProperty("line.separator"));
    fr.write("AAAAAAAAAAA");
    fr.close();
    }

  • How to insert new line in a text file

    hi all,
    i wnat to know how can i insert a new line in a text file using java.
    for example i want the formate of the text like this
    1 2 3
    4 5 6
    until now i know only how to insert data but not new line.
    Thanks in advandce

    Hi you can put a new line in a text file using System.getProperty("line.separator"). This implementation will work for every OS.
    import java.io.*;
    class Demo{
    public static void main(String args[]) throws Exception {
    FileWriter fr = new FileWriter("FileDemo.txt");
         fr.write("AAAAAAAAAA");
    fr.write(System.getProperty("line.separator"));
    fr.write("AAAAAAAAAAA");
    fr.close();
    }

  • Reading a Random Line from a Text File

    Hello,
    I have a program that reads from a text file words. I currently have a text file around 800KB of words. The problem is, if I try to load this into an arraylist so I can use it in my application, it takes wayy long to load. I was wondering if there was a way to just read a random line from the text file.
    Here is my code, and the text file that the program reads from is called 'wordFile'
    import java.awt.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    public class WordColor extends JFrame{
         public WordColor(){
              super("WordColor");
              setSize(1000,500);
              setVisible(true);
              add(new WordPanel());
         public static void main(String[]r){
              JFrame f = new WordColor();
    class WordPanel extends JPanel implements KeyListener{
         private Graphics2D pane;
         private Image img;
         private char[]characterList;
         private CharacterPosition[]positions;
         private int charcounter = 0;
         private String initialWord;
         private File wordFile = new File("C:\\Documents and Settings\\My Documents\\Java\\projects\\WordColorWords.txt");
         private FontMetrics fm;
         private javax.swing.Timer timer;
         public final static int START = 20;
         public final static int delay = 10;
         public final static int BOTTOMLINE = 375;
         public final static int buffer = 15;
         public final static int distance = 4;
         public final static Color[] colors = new Color[]{Color.red,Color.blue,Color.green,Color.yellow,Color.cyan,
                                                                          Color.magenta,Color.orange,Color.pink};
         public static String[] words;
         public static int descent;
         public static int YAXIS = 75;
         public static int SIZE = 72;
         public WordPanel(){
              words = readWords();
              setLayout(new BorderLayout());
              initialWord = getWord();
              characterList = new char[initialWord.length()];
              for (int i=0; i<initialWord.length();i++){
                   characterList[i] = initialWord.charAt(i);
              setFocusable(true);
              addKeyListener(this);
              timer = new javax.swing.Timer(delay,new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        YAXIS += 1;
                        drawWords();
                        if (YAXIS + descent - buffer >= BOTTOMLINE) lose();
                        if (allColorsOn()) win();
         public void paintComponent(Graphics g){
              super.paintComponent(g);
              if (img == null){
                   img = createImage(getWidth(),getHeight());
                   pane = (Graphics2D)img.getGraphics();
                   pane.setColor(Color.white);
                   pane.fillRect(0,0,getWidth(),getHeight());
                   pane.setFont(new Font("Arial",Font.BOLD,SIZE));
                   pane.setColor(Color.black);
                   drawThickLine(pane,getWidth(),5);
                   fm = g.getFontMetrics(new Font("Arial",Font.BOLD,SIZE));
                   descent = fm.getDescent();
                   distributePositions();
                   drawWords();
                   timer.start();
              g.drawImage(img,0,0,this);
         private void distributePositions(){
              int xaxis = START;
              positions = new CharacterPosition[characterList.length];
              int counter = 0;
              for (char c: characterList){
                   CharacterPosition cp = new CharacterPosition(c,xaxis, Color.black);
                   positions[counter] = cp;
                   counter++;
                   xaxis += fm.charWidth(c)+distance;
         private void drawThickLine(Graphics2D pane, int width, int thickness){
              pane.setColor(Color.black);
              for (int j = BOTTOMLINE;j<BOTTOMLINE+1+thickness;j++){
                   pane.drawLine(0,j,width,j);
         private void drawWords(){
              pane.setColor(Color.white);
              pane.fillRect(0,0,getWidth(),getHeight());
              drawThickLine(pane,getWidth(),5);
              for (CharacterPosition cp: positions){
                   int x = cp.getX();
                   char print = cp.getChar();
                   pane.setColor(cp.getColor());
                   pane.drawString(""+print,x,YAXIS);
              repaint();
         private boolean allColorsOn(){
              for (CharacterPosition cp: positions){
                   if (cp.getColor() == Color.black) return false;
              return true;
         private Color randomColor(){
              int rand = (int)(Math.random()*colors.length);
              return colors[rand];
         private void restart(){
              charcounter = 0;
              for (CharacterPosition cp: positions){
                   cp.setColor(Color.black);
         private void win(){
              timer.stop();
              newWord();
         private void newWord(){
              pane.setColor(Color.white);
              pane.fillRect(0,0,getWidth(),getHeight());
              repaint();
              drawThickLine(pane,getWidth(),5);
              YAXIS = 75;
              initialWord = getWord();
              characterList = new char[initialWord.length()];
              for (int i=0; i<initialWord.length();i++){
                   characterList[i] = initialWord.charAt(i);
              distributePositions();
              charcounter = 0;
              drawWords();
              timer.start();
         private void lose(){
              timer.stop();
              pane.setColor(Color.white);
              pane.fillRect(0,0,getWidth(),getHeight());
              pane.setColor(Color.red);
              pane.drawString("Sorry, You Lose!",50,150);
              repaint();
              removeKeyListener(this);
              final JPanel p1 = new JPanel();
              JButton again = new JButton("Play Again?");
              p1.add(again);
              add(p1,"South");
              p1.setBackground(Color.white);
              validate();
              again.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        remove(p1);
                        addKeyListener(WordPanel.this);
                        newWord();
         private String getWord(){
              int rand = (int)(Math.random()*words.length);
              return words[rand];
         private String[] readWords(){
              ArrayList<String> arr = new ArrayList<String>();
              try{
                   BufferedReader buff = new BufferedReader(new FileReader(wordFile));
                   try{
                        String line = null;
                        while (( line = buff.readLine()) != null){
                             line = line.toUpperCase();
                             arr.add(line);
                   finally{
                        buff.close();
              catch(Exception e){e.printStackTrace();}
              Object[] objects = arr.toArray();
              String[] words = new String[objects.length];
              int count = 0;
              for (Object o: objects){
                   words[count] = (String)o;
                   count++;
              return words;
         public void keyPressed(KeyEvent evt){
              char tempchar = evt.getKeyChar();
              String character = ""+tempchar;
              if (character.equalsIgnoreCase(""+positions[charcounter].getChar())){
                   positions[charcounter].setColor(randomColor());
                   charcounter++;
              else if (evt.isShiftDown()){
                   evt.consume();
              else{
                   restart();
              drawWords();
         public void keyTyped(KeyEvent evt){}
         public void keyReleased(KeyEvent evt){}
    class CharacterPosition{
         private int xaxis;
         private char character;
         private Color color;
         public CharacterPosition(char c, int x, Color col){
              xaxis = x;
              character = c;
              color = col;
         public int getX(){
              return xaxis;
         public char getChar(){
              return character;
         public Color getColor(){
              return color;
         public void setColor(Color c){
              color = c;
    }

    I thought that maybe serializing the ArrayList might be faster than creating the ArrayList by iterating over each line in the text file. But alas, I was wrong. Here's my code anyway:
    class WordList extends ArrayList<String>{
      long updated;
    WordList readWordList(File file) throws Exception{
      WordList list = new WordList();
      BufferedReader in = new BufferedReader(new FileReader(file));
      String line = null;
      while ((line = in.readLine()) != null){
        list.add(line);
      in.close();
      list.updated = file.lastModified();
      return list;
    WordList wordList;
    File datFile = new File("words.dat");
    File txtFile = new File("input.txt");
    if (datFile.exists()){
      ObjectInputStream input = new ObjectInputStream(new FileInputStream(datFile));
      wordList = (WordList)input.readObject();
      if (wordList.updated < txtFile.lastModified()){
        //if the text file has been updated, re-read it
        wordList = readWordList(txtFile);
        ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(datFile));
        output.writeObject(wordList);
        output.close();
    } else {
      //serialized list does not exist--create it
      wordList = readWordList(txtFile);
      ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(datFile));
      output.writeObject(wordList);
      output.close();
    }The text file contained one random sequence of letters per line. For example:
    hwnuu
    nhpgaucah
    zfbylzt
    hwnc
    gicgwkhStats:
    Text file size: 892K
    Serialized file size: 1.1MB
    Time to read from text file: 795ms
    Time to read from serialized file: 1216ms

  • Reading one line from a text file into an array

    i want to read one line from a text file into an array, and then the next line into a different array. both arays are type string...i have this:
    public static void readAndProcessData(FileInputStream stream){
         InputStreamReader iStrReader = new InputStreamReader (stream);
         BufferedReader reader = new BufferedReader (iStrReader);
         String line = "";          
         try{
         int i = 0;
              while (line != null){                 
                   names[i] = reader.readLine();
                   score[i] = reader.readLine();
                   line = reader.readLine();
                   i++;                
              }catch (IOException e){
              System.out.println("Error in file access");
    this section calls it:
    try{                         
         FileInputStream stream = new FileInputStream("ISU.txt");
              HighScore.readAndProcessData(stream);
              stream.close();
              names = HighScore.getNames();
              scores = HighScore.getScores();
         }catch(IOException e){
              System.out.println("Error in accessing file." + e.toString());
    it gives me an array index out of bounds error

    oh wait I see it when I looked at the original quote.
    They array you made called names or the other one is prob too small for the amount of names that you have in the file. Hence as I increases it eventually goes out of bounds of the array so you should probably resize the array if that happens.

  • Best way to remove last line-feed in text file

    What is the best way to remove last line-feed in text file? (so that the last line of text is the last line, not a line-feed). The best I can come up with is: echo -n "$(cat file.txt)" > newfile.txt
    (as echo -n will remove all trailing newline characters)

    What is the best way to remove last line-feed in text file? (so that the last line of text is the last line, not a line-feed). The best I can come up with is: echo -n "$(cat file.txt)" > newfile.txt
    (as echo -n will remove all trailing newline characters)
    According to my experiments, you have removed all line terminators from the file, and replaced those between lines with a space.
    That is to say, you have turned a multi-line file into one long line with no line terminator.
    If that is what you want, and your files are not very big, then your echo statement might be all you need.
    If you need to deal with larger files, you could try using the 'tr' command, and something like
    tr '
    ' ' ' <file.txt >newfile.txt
    The only problem with this is, it will most likely give you a trailing space, as the last newline is going to be converted to a space. If that is not acceptable, then something else will have to be arranged.
    However, if you really want to maintain a multi-line file, but remove just the very last line terminator, that gets a bit more complicated. This might work for you:
    perl -ne '
    chomp;
    print "
    " if $n++ != 0;
    print;
    ' file.txt >newfile.txt
    You can use cat -e to see which lines have newlines, and you should see that the last line does not have a newline, but all the others still do.
    I guess if you really did mean to remove all newline characters and replace them with a space, except for the last line, then a modification of the above perl script would do that:
    perl -ne '
    chomp;
    print " " if $n++ != 0;
    print;
    ' file.txt >newfile.txt
    Am I even close to understanding what you are asking for?

  • Random Line reading in text file

    I am trying to read a random line in a text file but every time i read it it reads first line of the file any one can help me what is the problem in the code is or provide me with a new code.
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
                   File file = new File("word.txt");
                   if(!file.exists())
                        System.out.println("File does not exist.");
                        System.exit(0);
                   try{
                        //Open the file for reading
                        RandomAccessFile raf = new RandomAccessFile(file, "r");
    raf.seek(file.length());     //Seek to end of file
                        System.out.println("Read full line: " + raf.readLine());
    //str2 is a String
                        str2 = str2 + raf.readLine();
                        System.out.println(""+str2);
                        raf.close();
                        System.out.println("Successfully");
                   catch(IOException ioe)
                        System.out.println(ioe.getMessage());
    my text file look like in this format
    mind
    hate
    Abhor
    Bigot
    narrow
    prejudiced
    person
    Counterfeit
    fake
    false
    give
    voting
    rights
    Hamper
    hinder
    obstruct
    Kindle
    to
    start
    fire
    harmful
    poisonous
    lethal

    Next time when posting code, please use code tags: http://forum.java.sun.com/help.jspa?sec=formatting
    A RandomAccessFile has nothing to do with getting a (pseudo) random line number from a file.
    You should also split things up in separate methods:
    - a method for counting the number of lines in a file;
    - a method to get the N-th line from a file.
    In your main method, you call the method which counts the number of lines N in a file and then generate a (pseudo) random number between 1 and N. Use the java.util.Random class for this.
    When you have generated that number, call the other method to get that specific line number.
    Here's a small start:
    import java.io.*;
    import java.util.*;
    public class Main {
        public static String getLineNumber(int number) throws FileNotFoundException {
            // your code here
        public static int countLines(String fileName) throws FileNotFoundException {
            // your code here
        public static void main(String[] args) throws Exception {
            int numberLines = countLines("word.txt");
            Random generator = new Random();
            int randomNumber = generator.nextInt(numberLines)+1;
            String randomLine = getLineNumber(randomNumber);
            System.out.println("Line "+randomNumber+" = '"+randomLine+"'");
    }In both methods, you can use the java.util.Scanner class to read lines from the file.
    Have a look at the API docs of the Scanner class:
    http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html (including code samples!)
    Good luck.

  • File adapter-How to set line break in text file-split record into two lines

    Dear Guru's,
    I have to solve following problem with XML (with mulitiple records) to TEXT file scenario using file adapter. I have to output for ever ONE data record in XML always two identical lines in text file. Second line should have a little bit different mapping in few fields like date,... So I did duplicate fileds in my output structure in mapping and need to know how to set line break in the middle and see half of structure in first line and next structure half in second line
    My output structure in mapping is:
    CASHFLOW
    - INTERFACE
    - GESELLSCHAFT
    - ANWENDUNG
    - PRODUKT
    - VERTRAG
    - BETRAG
    - WAEHRUNG
    - DIRECTION
    - BEWEGUNGSTYP
    - FAELLIGKEIT
    - ZINSFESTSTELLUNG
    - ZAHLUNGSTAG
    - RENDITE
    - INTERFACE2
    - GESELLSCHAFT2
    - ANWENDUNG2
    - PRODUKT2
    - VERTRAG2
    - BETRAG2
    - WAEHRUNG2
    - DIRECTION2
    - BEWEGUNGSTYP2
    - FAELLIGKEIT2
    - ZINSFESTSTELLUNG2
    - ZAHLUNGSTAG2
    - RENDITE2
    Question is how can I set on receiving file adapter in Content Conversion Parameters that fields from first structure half INTERFACE...RENDITE should be outputed in one line and fields from second half of structure INTERFACE2...RENDITE2 should start on second line in final text file.
    I'm getting at the moment one line only and I need to know how can set line break so that second line starting with INTERFACE2(CA)...RENDITE2 will start in new line.
    CA,"0100","7","512",20090127010001,-12454762586.6800,"EUR",2,12,2009-01-28,2009-01-27,2009-01-28,"0.0000000",CA,"0100","7","512",20090127010001,-12454762586.6800,"EUR",1,10,2009-01-27,2009-01-27,2009-01-27,"0.0000000"
    This should be final output:
    CA,"0100","7","512",20090127010001,-12454762586.6800,"EUR",2,12,2009-01-28,2009-01-27,2009-01-28,"0.0000000"
    CA,"0100","7","512",20090127010001,-12454762586.6800,"EUR",1,10,2009-01-27,2009-01-27,2009-01-27,"0.0000000"
    My file adapter settings:
    RecordsetStructure=CASHFLOW
    CASHFLOW.fieldNames=INTERFACE,GESELLSCHAFT,ANWENDUNG,PRODUKT,VERTRAG,BETRAG,WAEHRUNG,DIRECTION,BEWEGUNGSTYP,FAELLIGKEIT,ZINSFESTSTELLUNG,ZAHLUNGSTAG,RENDITE
    CASHFLOW.fieldSeparator=,
    CASHFLOW.endSeparator='nl'
    CASHFLOW.fieldNames=INTERFACE2,GESELLSCHAFT2,ANWENDUNG2,PRODUKT2,VERTRAG2,BETRAG2,WAEHRUNG2,DIRECTION2,BEWEGUNGSTYP2,FAELLIGKEIT2,ZINSFESTSTELLUNG2,ZAHLUNGSTAG2,RENDITE2
    CASHFLOW.fieldSeparator=,
    It wont help if I add two identical structures in mapping because in output i would see for multiple entries section with first lines only and after that section with second lines only. And CASHFLOW is one part of more complex mapping ...
    (This is final output structure RecordsetStructure=HEADER,CASHFLOW,CONDITION,REFERENCE,CONTRACT - more sections with different data and all these should have duplicate lines at the end)
    Thanks a lot for any help
    Cheers
    Marian
    Edited by: Marian  Luscon on Jul 14, 2009 11:44 AM

    Hi Ivan,
    right, I did test just for sure.
    Putting constant 'nl' into field CASHFLOW-INTERFACE1 didnt help - still getting one line instead two lines.
    CA ,"0100" ,"7" ,"512" ,20090127GTP101 ,-12454762586.6800 ,"EUR" ,2 ,12 ,2009-01-28 ,2009-01-27 ,2009-01-28 ,"0.0000000" ,'nl' ,"GTP1" ,"7" ,"512" ,20090127GTP101 ,-12454762586.6800 ,"EUR" ,1 ,10 ,2009-01-27 ,2009-01-27 ,2009-01-27 ,"0.0000000"
    So there is still question. Is there any way (mapping,...) how to output always 2 lines in text file for one record in XML. It always does 1 record in mapping structure = 1 line but we need 2 lines ...
    Example:
    Input: 4 records in XML
    Output: 8 lines in final text file ...
    Thanks to you all guys
    Marian

  • How to read every line from a text file???

    How can i read every line from my text file ("eka.txt")
    now it only reads the first line and prints it out.
    What is wrong with this?
    import java.io.*;
    import java.util.*;
    class Testi{
         public static void main(String []args)throws IOException {
         BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
    File inputFile = new File ("eka.txt");
    FileReader fis =new FileReader(inputFile);
    BufferedReader bis = new BufferedReader(fis);
    String test=bis.readLine();
    String tmp= "";
    while((bis.readLine().trim() != null)) {
    int spacefound=0;
    int l=test.indexOf(" ");
         for(int i=0;i<test.length();i++){
         char c=test.charAt(i);
         if(c!=' ') tmp+=""+c;
         if(c==' ' && (spacefound<1) && !(tmp.equals(""))){
         tmp+=""+c;
         spacefound++;
         if(tmp.length()==l) {
         System.out.println(tmp);
         tmp="";
         spacefound=0;
         if(tmp.length()<l){
         for(int i=0;i<=(l-tmp.length());i++)
         tmp+=""+' ';
         System.out.println(tmp);

    Try this code, Hope it servers your purpose.
    import java.io.*;
    import java.util.*;
    class Testi {
         public static void main(String []args)throws IOException {
              BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
              File inputFile = new File ("Eka.txt");
              FileReader fis =new FileReader(inputFile);
              BufferedReader bis = new BufferedReader(fis);
              String test=bis.readLine();
              while(test != null) {
                   StringTokenizer st = new StringTokenizer(test," ");
                   while(st.hasMoreTokens())
                        System.out.println(st.nextToken());
                   test = bis.readLine();
    }Sudha

  • Passing lines in a text file to an array

    Hi,
    I did a search on this, looked through the tutorials. I want to read in a line from a text file and pass it to an array. here's my code:
    package pack1;
    import java.io.File;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.util.Scanner;
    public class CDSort {
          * write a program that will read a bunch of cd's from a textfile,
          * count how many there are, and figure out how many cd boxes I will need based
          * on a fixed amount that will fit in each box. The cd's should be sorted alphabetically,
          * and each should be placed in a numbered box, and have a numbered position within that box
         public static void main(String[] args)throws Exception {
              java.io.File cdlist = new java.io.File("files/cd-list.txt");
              FileReader infile = new FileReader(cdlist);
              FileWriter outfile = new FileWriter("files/newlist.txt");
              if (cdlist.exists()){
                   System.out.println( cdlist.getName() + " exists at " + cdlist.getAbsolutePath());
                   System.out.println("this file was last modified on: " + new java.util.Date(cdlist.lastModified()));
                   int c;
                   while ((c = infile.read()) != -1) {
                        System.out.println(c);
                        String [] textArray = new String[99];
                             for(int i =0; i<textArray.length; i++){
                                  // trying to pass text to array here: I tried this, but got an error:
                                  //textArray[i] = infile.read(c);
                                  // i added this statement so I could see what the value of the array was on the console
                                  System.out.println(textArray[i] + i);
                        outfile.write(c);
                   infile.close();
                   outfile.close();
              } else
                   System.exit(0);
    }This is probably a pretty basic question, but my hunting arround hasn't really yielded anything.

    okay, here's what I did, this seems to work.
    package pack1;
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.PrintStream;
    public class CDSort {
          * write a program that will read a bunch of cd's from a textfile,
          * count how many there are, and figure out how many cd boxes I will need based
          * on a fixed amount that will fit in each box. The cd's should be sorted alphabetically,
          * and each should be placed in a numbered box, and have a numbered position within that box
         public static void main(String[] args)throws Exception {
              java.io.File cdlist = new java.io.File("cd-list.txt");
              FileReader infile = new FileReader(cdlist);
              //FileWriter outfile = new FileWriter("newlist.txt");
              BufferedReader br = new BufferedReader(infile);
              BufferedWriter out = new BufferedWriter(new FileWriter("newlist.txt"));
              if (cdlist.exists()){
                   System.out.println( cdlist.getName() + " exists at " + cdlist.getAbsolutePath());
                   System.out.println("this file was last modified on: " + new java.util.Date(cdlist.lastModified()));
                   // while loop was here, I removed it.
                   String [] textArray = new String[99];
                   String line;
                   int lineNum = 0;
                   while ((line = br.readLine()) != null){
                        textArray[lineNum++] = line;
                        System.out.println(line);
                   int numOfCds = 1;
                   int boxNum = 1;
                   int boxPos = 1;
                   int cdsPerBox = 20;
                   out.write("Contents of Box " + boxNum);
                   out.newLine();
                   out.newLine();
                   for(int i = 0; i<textArray.length; i++){
                        out.write(textArray[i] + " box position: " + boxPos + "\n");
                        out.newLine();
                        boxPos++;
                        numOfCds++;
                        if (boxPos >= cdsPerBox){
                             boxNum++;
                             out.newLine();
                             out.newLine();
                             out.write("Contents of Box " + boxNum);
                             out.newLine();
                             out.newLine();
                             boxPos = 1;
                   infile.close();
                   out.close();
              } else {
                   System.out.println("file not found, program terminating");
                   System.exit(0);
    }thanks for all your help.
    bp

  • Read the first word of each line in a text file

    i need to read the first word of each line of a text file.
    i know of line.split() but not actually sure how i would go about using it
    Any help most appreciated
    Many Thanks
    Ben

    Hi thanks for the reply!
    this is what i tried... and it still doesn't get me the first word of each line!
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.Color;
    import java.awt.event.ActionEvent;
    import java.io.*;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import javax.swing.text.*;
    import javax.swing.event.*;
    import java.util.Calendar;
    import java.util.Scanner;
    import java.util.Vector;
    import java.text.SimpleDateFormat;
    import java.net.InetAddress;
    import java.net.UnknownHostException;
    import java.io.BufferedReader;
    public class testing {
         Vector progs=new Vector();
         Vector rand=new Vector();
         String[] tmp = new String [2];
         String str;
         String str2="ewerwer";
         String str3;
         public void programTest()
                   try
                             BufferedReader in = new BufferedReader(new FileReader("progList.log"));
                             while ((str = in.readLine()) != null)
                                  progs.add(str);
                        catch(IOException e)
                             System.out.println("cannot read file");
         //////THE ISSUES IS HERE....I WANT TO GET THE FIRST WORD FROM EACH LINE OF THE FILE!!!     
              try
                             BufferedReader in2 = new BufferedReader(new FileReader("eventLog.log"));
                             while ((str = in2.readLine()) != null)
                                  tmp = str.split(" ");
                                  System.out.println(tmp[0]);
                        catch(IOException e)
                             System.out.println("cannot read file");
    public static void main(String[] args)
                 testing B = new testing();
                 B.programTest();
               //  B.fileToVector();
                 //B.LoginWindow();
               //B.anomDetect();
    }//end class

  • Add header line to the text file in receiver file adapter

    Hello Experts,
    I have to add a new line to the text file generated at the receiver end.
    My structure is
    Record
       Item......0-unbounded
             field1
             field2
             field3
    I have defined below parameters in receiver FCC.
    RecordSet Structure : Record,Item
    Item.fieldSeparator : ;
    Record.fieldSeparator : nl
    Record.endSeparator : '0x0D''0x0A' ( this is to get a carriage return at the end of the file)
    Item.addHeaderLine : 1
    With the above configuration, i am getting the desired output with NO header line.
    Please help.
    Thanks,
    Swetha.

    Hi, it looks like that the headerline "specification is only permitted if exactly one structure is defined." Please check [SAP help under Define Parameters for Recordset Structures|http://help.sap.com/saphelp_nw73/helpdata/en/44/686e687f2a6d12e10000000a1553f6/frameset.htm].
    One solution would be to generate the header fields in the message payload. Generate an additional first line containing the header names, e.g.
    <Item>
    <field1>Header1
    <field2>Header2
    <field3>Header3

  • Retrieving certain line from a text file

    Hi,
    I would like to know on how to read a specific line from a text file using NetBeans IDE 6.1? Below is the content of my text file and my code.I will appreciate if anyone can help. Thank in advance= D
    Matrix1.text
    <matrix>
    rows = 2
    cols = 2
    1 2
    2 4
    </matrix>
    I would like to retrieve the interger 1,2,2,4.
    MyCode.java
    import java.io.IOException;
    import java.io.FileReader;
    import java.io.BufferedReader;
    import java.io.FileNotFoundException;
    class Matrix {
    double [][] element;
    static void getFile(String fileName) throws IOException{
    int counter = 0;
    BufferedReader br = null;
    try{
    br = new BufferedReader(new FileReader(fileName));
    String line = br.readLine();
    while (line != null){
    line = br.readLine();
    System.out.println(line);
    counter ++;
    System.out.println("Total line : " + counter);
    br.close();
    }catch(FileNotFoundException ex){
    System.out.println(ex.getMessage());
    }

    Wonders wrote:
    Thank for reply=D
    Yap the row and column will change but i had already parse these lines into my code. However, i am still figuring on how to get the integer number 1,2,2,4 of the text file using while loop and not include the "</matrix>" in the reading. Can this be done?If the numbers you want are at fixed byte positions in the file that are known ahead of time, you can use java.io.RandomAccessFile to skip to those positions. However, that seems unlikely.
    If, as is the more likely case, those are not at fixed positions, you'll have to read everything preceding them. (Note that this is not a Java issue. This is how file I/O works.) You'll need to ignore the lines that are meaningless to you (read those lines and do nothing with them) figure out, by whatever rules you have--line numbers, preceding tokens, whatever--when you're at the lines you do care about, and then read and process those lines accordingly.

  • Partial Overwrite for text file

    I am trying to figure out how to overwrite a single line in a text file for an appointment program I am making. I am having a difficult time with this because I can't figure out how to overwrite a single line. If I could solve this, I could get my delete button (it's GUI) working and my edit button working. Thanks in advance!
    -Vegunks

    The short answer is that "overwriting" in a text file is problematic, and for a couple reasons:
    1. Often you want to replace 50 characters with 70 characters or 30 characters and you can't make a file simply grow or shrink like that.
    2. Your text encoding may have some surprises in store for you. Common encodings like UTF-8 can encode a single character as 1, 2 or three bytes depending on its value, so even if you think you are replacing 50 characters with 50 characters, you may be replacing 80 bytes with 84 bytes.
    The solution is to rewrite the entire file. More precisely:
    1. create a new file and write to it.
    2. delete the old file.
    3. rename the new file to take the place of the old file.
    edit: too slow!

Maybe you are looking for