此代码应该从源文件中读取一个字符;转换为ASCII int值;加1;转换回角色;写入目标文件。
我的目标文件中没有显示任何内容。
现在,我并不担心获得大于255的ASCII值或效率。
import java.io.*;
public class ReadAFile {
public static void main(String[] args) {
try {
File myFile = new File("source.txt");
FileReader fileReader = new FileReader(myFile);
BufferedReader reader = new BufferedReader(fileReader);
int character;
int shift = 1;
while ((character = reader.read()) != -1) {
character = (int) reader.read() + shift;
WriteAFile(Character.toString((char) character));
}
reader.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void WriteAFile(String line) {
try {
FileWriter writer = new FileWriter("destination.txt");
writer.write(line);
writer.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
答案 0 :(得分:1)
只需将代码形式放入@Deepak所说的内容:
public static void main(String[] args)
{
try
{
File myFile = new File("c:\\temp\\source.txt"));
File outputFile = new File("c:\\temp\\output.txt");
FileWriter writer = new FileWriter(outputFile);
FileReader fileReader = new FileReader(myFile);
BufferedReader reader = new BufferedReader(fileReader);
try
{
int character;
int shift = 1;
while ((character = reader.read()) != -1)
{
character = (int) reader.read() + shift;
writer.write(Character.toString((char) character));
}
}
finally
{
writer.close();
reader.close();
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
还要确保指定输出路径。
答案 1 :(得分:0)
您正在覆盖每个角色的文件。这既低效又无法满足您的需求。在程序期间保持FileWriter
打开,并在finally
块中关闭它。
如果你必须写每个字符,请使用append标志告诉作者不要覆盖该文件。