can you please trasnfer this code to java #include <iostream> #include <fstream>
ID: 3884920 • Letter: C
Question
can you please trasnfer this code to java
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
// Input file characters.
string alphas = "ABCDEFGHIJKLMNOPQRSTUVWXYZ ";
// Characters we should write in output file.
string ciphers = "XEv&rz@6\85e:|D)YLQ+`_nb#<^ ";
// variable to hold every read character.
char readChar;
// Input stream to read in data.
fstream inp_file("cipher.txt", fstream::in);
// Output stream to encrypt.
fstream out_file("out.txt", fstream::out);
// iterates through whole file char by char.
while (inp_file >> noskipws >> readChar) {
// finds index.
size_t alphas_index = alphas.find(readChar);
// if exists in range.
if (alphas_index < alphas.length()) {
// output the shifted character.
out_file << ciphers[alphas_index];
} else {
// output the same character.
out_file << readChar;
}
}
// Close files
inp_file.close();
out_file.close();
return 0;
}
Explanation / Answer
Here is code:
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Cipher {
public static void main(String[] args) {
try {
// Input file characters.
String alphas = "ABCDEFGHIJKLMNOPQRSTUVWXYZ ";
// Characters we should write in output file.
String ciphers = "XEv&rz@6\85e:|D)YLQ+`_nb#<^ ";
FileReader reader = new FileReader("cipher.txt");
int character;
FileWriter writer = new FileWriter("output.txt", false);
// read character by character
while ((character = reader.read()) != -1) {
// finds the index
int index = alphas.indexOf((char)character);
// if not -1 means in range of alphas
if (index != -1) {
writer.write(ciphers.charAt(index));
}else
{
writer.write((char)character);
}
}
// close reader
reader.close();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output:
Input file :
ABCDEFGHIJKLMNOPQRSTUVWXYZ
Output:
XEv&rz@685e:|D)YLQ+`_nb#<
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.