所以我需要帮助增加文件中的所有字符。整个文件能够从用户那里读取并获取所有信息,但是当涉及实际增加(本例)文件中的所有字符时,它只输出一个空白文件。
此程序的目标是读入用户文件,从文件中获取所有文本,并将字母增加或减少一个。所以A现在是B或B现在是C或者反之亦然B现在是A或C现在是B.当它导出/关闭文件时它只是空白。
以下是代码的一部分: while(fileIn.hasNext()) { letter.add(fileIn.next());
for (int i = letter.size() - 1; i >= 0; i--)
{
ch = letter.get(i).charAt(0);
ch--;
fileout1.println(ch);
}
//Makes a new line at end of line
System.out.println();
}
整个代码如下:
import java.util.*;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.File;
import java.util.ArrayList;
public class Assignment9
{
public static void main (String[] args)
{
Scanner in = new Scanner (System.in);
Scanner fileIn;
File f;
char ch = 65;
String fileName = "";
boolean userA = false;
String usersChoice = "";
ArrayList<String> letter = new ArrayList<String>();
try
{
System.out.println("Please enter the file name that you would like encrypted/decrypted: ");
fileName = in.nextLine();
//Builds the file and attaches the Scanner
f = new File (fileName);
fileIn = new Scanner (f);
PrintWriter fileout1 = new PrintWriter ("decrypt.txt");
PrintWriter fileout2 = new PrintWriter ("encrypt.txt");
System.out.println("Would you like to Decrypt or Encrypt the file?");
usersChoice = in.nextLine();
userA = true;
//Loop through the file and translate the characters
if (usersChoice.equalsIgnoreCase("Decrypt"))
{
while (fileIn.hasNext())
{
letter.add(fileIn.next());
for (int i = letter.size() - 1; i >= 0; i--)
{
ch = letter.get(i).charAt(0);
ch--;
fileout1.println(ch);
}
//Makes a new line at end of line
System.out.println();
}
//Decrease every letter by 1 (runs backwords)
System.out.println("Decrypt.txt has been created.");
fileout1.close();
}
//encrypts the file by increasing by 1
if (usersChoice.equalsIgnoreCase("encrypt"))
{
while (fileIn.hasNext())
{
letter.add(fileIn.next());
}
//Decrease every letter by 1 (runs backwords)
for (int i = letter.size() -1; i >= 0; i--)
{
System.out.println(letter);
ch --;
}
System.out.println("Encrypted.txt has been created.");
fileout2.close();;
}
} //end of try
catch (FileNotFoundException e)
{
System.out.println("Sorry invalid file, please try again");
fileName = in.nextLine();
}
} // end of main
} //end of program
答案 0 :(得分:0)
您可以执行以下操作,
FileReader fr = null;
FileWriter fw = null;
int c;
try {
fr = new FileReader("C:\\Zia\\test.txt");
fw = new FileWriter("C:\\Zia\\Result.txt");
while ((c = fr.read()) != -1) {
if(c!=32)
fw.write((char)--c);
else
fw.write((char)c);
}
} catch(IOException e) {
e.printStackTrace();
} finally {
close(fr);
close(fw);
}
我的test.txt
文件包含以下内容,
Hello How are you doing.
和result.txt在将char减少一之后包含以下结果。
Gdkkn Gnv `qd xnt cnhmf-
您可以为Reader和writer的文件交换文件名,并将char增加1以验证解密。