1. /*
  2. * Copyright 2003-2004 The Apache Software Foundation
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. *
  16. */
  17. package org.apache.tools.ant.util;
  18. import java.io.Reader;
  19. import java.io.IOException;
  20. import org.apache.tools.ant.ProjectComponent;
  21. /**
  22. * class to tokenize the input as lines seperated
  23. * by \r (mac style), \r\n (dos/windows style) or \n (unix style)
  24. * @since Ant 1.6
  25. */
  26. public class LineTokenizer extends ProjectComponent
  27. implements Tokenizer {
  28. private String lineEnd = "";
  29. private int pushed = -2;
  30. private boolean includeDelims = false;
  31. /**
  32. * attribute includedelims - whether to include
  33. * the line ending with the line, or to return
  34. * it in the posttoken
  35. * default false
  36. * @param includeDelims if true include /r and /n in the line
  37. */
  38. public void setIncludeDelims(boolean includeDelims) {
  39. this.includeDelims = includeDelims;
  40. }
  41. /**
  42. * get the next line from the input
  43. *
  44. * @param in the input reader
  45. * @return the line excluding /r or /n, unless includedelims is set
  46. * @exception IOException if an error occurs reading
  47. */
  48. public String getToken(Reader in) throws IOException {
  49. int ch = -1;
  50. if (pushed != -2) {
  51. ch = pushed;
  52. pushed = -2;
  53. } else {
  54. ch = in.read();
  55. }
  56. if (ch == -1) {
  57. return null;
  58. }
  59. lineEnd = "";
  60. StringBuffer line = new StringBuffer();
  61. int state = 0;
  62. while (ch != -1) {
  63. if (state == 0) {
  64. if (ch == '\r') {
  65. state = 1;
  66. } else if (ch == '\n') {
  67. lineEnd = "\n";
  68. break;
  69. } else {
  70. line.append((char) ch);
  71. }
  72. } else {
  73. state = 0;
  74. if (ch == '\n') {
  75. lineEnd = "\r\n";
  76. } else {
  77. pushed = ch;
  78. lineEnd = "\r";
  79. }
  80. break;
  81. }
  82. ch = in.read();
  83. }
  84. if (ch == -1 && state == 1) {
  85. lineEnd = "\r";
  86. }
  87. if (includeDelims) {
  88. line.append(lineEnd);
  89. }
  90. return line.toString();
  91. }
  92. /**
  93. * @return the line ending character(s) for the current line
  94. */
  95. public String getPostToken() {
  96. if (includeDelims) {
  97. return "";
  98. }
  99. return lineEnd;
  100. }
  101. }