1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29 package uk.ac.rdg.resc.jstyx.gridservice.tutorial;
30
31 import java.io.InputStream;
32 import java.io.FileInputStream;
33 import java.io.FileOutputStream;
34 import java.io.InputStreamReader;
35 import java.io.BufferedReader;
36 import java.io.PrintStream;
37 import java.io.IOException;
38
39 import com.martiansoftware.jsap.JSAP;
40 import com.martiansoftware.jsap.JSAPException;
41 import com.martiansoftware.jsap.JSAPResult;
42 import com.martiansoftware.jsap.FlaggedOption;
43
44 /***
45 * Simple program that reads input one line at a time from standard input, reverses
46 * the characters in each line, then prints the reversed line to the standard output
47 *
48 * @author Jon Blower
49 * $Revision: 596 $
50 * $Date: 2006-02-22 13:30:19 +0000 (Wed, 22 Feb 2006) $
51 * $Log$
52 * Revision 1.1 2006/02/22 13:30:19 jonblower
53 * Initial import
54 *
55 */
56 public class Reverse
57 {
58
59 public static void main (String[] args)
60 {
61 try
62 {
63
64 JSAP jsap = new JSAP();
65
66 jsap.registerParameter(new FlaggedOption("inputfile", JSAP.STRING_PARSER,
67 null, false, 'i', JSAP.NO_LONGFLAG));
68 jsap.registerParameter(new FlaggedOption("outputfile", JSAP.STRING_PARSER,
69 null, false, 'o', JSAP.NO_LONGFLAG));
70
71 JSAPResult result = jsap.parse(args);
72 InputStream in;
73 String inputName = result.getString("inputfile");
74 if (inputName == null)
75 {
76 in = System.in;
77 }
78 else
79 {
80 in = new FileInputStream(inputName);
81 }
82 PrintStream out;
83 String outputName = result.getString("outputfile");
84 if (outputName == null)
85 {
86 out = System.out;
87 }
88 else
89 {
90 out = new PrintStream(new FileOutputStream(outputName));
91 }
92 reverseLines(in, out);
93 }
94 catch (JSAPException jsape)
95 {
96 jsape.printStackTrace();
97 }
98 catch(IOException ioe)
99 {
100 ioe.printStackTrace();
101 }
102 }
103
104 /***
105 * Reads a line at a time from the given input stream, reverses the
106 * characters in each line and prints the reversed characters to the given
107 * PrintWriter
108 */
109 private static void reverseLines(InputStream in, PrintStream out) throws IOException
110 {
111 BufferedReader bufIn = new BufferedReader(new InputStreamReader(in));
112 String line;
113 do
114 {
115 line = bufIn.readLine();
116 if (line != null)
117 {
118 out.println(reverse(line));
119 }
120 } while (line != null);
121 }
122
123 /***
124 * Reverses the characters in the given string and returns the reversed
125 * string
126 */
127 private static String reverse(String inputStr)
128 {
129 StringBuffer newStr = new StringBuffer();
130 for (int i = inputStr.length() - 1; i >= 0; i--)
131 {
132 newStr.append(inputStr.charAt(i));
133 }
134 return newStr.toString();
135 }
136
137 }