In: Computer Science
Java Code using Stack
Write a program that opens a text file and reads its contents into a stack of characters, it should read character by character (including space/line change) and push into stack one by one. The program should then pop the characters from the stack and save them in a second text file. The order of the characters saved in the second file should be the reverse of their order in the first file.
Ex input file:
Good Morning!
Bye..
EX output file:
!gninroM dooG
...eyB
import java.io.*;
import java.util.*;
class Stack{
private static int top,maxsize;
private static char arr[];
//Stack creation using arrays.
Stack(int n){
this.maxsize=n;
top=-1;
arr=new char[maxsize];
}
//push character into stack
void push(char p){
char val=p;
top++;
arr[top]=val;
}
//pop character from stack
char pop(){
char o=arr[top];
top --;
return o;
}
}
public class File1{
public static void main (String [] args)throws IOException{
FileReader f=new FileReader("input.txt");
BufferedReader read=new BufferedReader(f);
String data;
try{
//creating output file.
File fi=new File("output.txt");
//if output file exists then it is deleted and creates new one.
if(fi.exists()){
fi.delete();
}
FileWriter d=new FileWriter("output.txt",true);
while((data=read.readLine())!=null){
Stack s=new Stack(data.length());
//pushing characters into stack.
for(int i=0;i<=data.length()-1;i++){
s.push(data.charAt(i));
}
//writing characters into output file.
for(int i=0;i<data.length();i++){
d.write(s.pop());
}
d.write("\n");
}
//closing output file to ensure security.
d.close();
}catch(Exception e){System.out.println(e);}
}
}
Note:- If your input file is in another location i.e., other than current working directory, then please specify path in the above code as follows:-
FileReader f=new FileReader("C:\\Users\\HP\\Desktop\\java\\input.txt");