要把txt文件中的字母abcdefghijklm转换成nopqrstuvwxyz。code 写出来了,但是为什么printout的只有最后一行。
[code=Java][/code]
import java.util.*;
import java.io.*;
public class Rot {
/**
* @param args
*/
public static void main(String[] args)throws IOException {
// TODO Auto-generated method stub
String FileName=readFileName("Please enter an input file name:");
Scanner infile = new Scanner (new File(FileName+".txt"));
String result=transformed(infile);
FileName=readFileName("Please enter an output file name:");
PrintWriter outfile=new PrintWriter(new FileWriter(FileName+".txt"));
System.out.println(result);
outfile.println(result);
infile.close();
outfile.close();
}
public static String readFileName(String msg){
Scanner inkey = new Scanner(System.in);
System.out.println(msg);
return inkey.nextLine();
}
public static String transformed(Scanner in)throws IOException{
String line=null;
int num=13;
while(in.hasNextLine()){
line=in.nextLine();
int count=0;
while(count<line.length()){
char letter=line.charAt(count);
if(letter>='a' && letter<'n')
letter+=num;
else if(letter>='n' && letter<='z')
letter-=num;
if(letter>='A' && letter<'N')
letter+=num;
else if(letter>='N' && letter<='Z')
letter-=num;
count++;
}
}
return line;
}
}
------解决方案--------------------
这就要用到传说中的IO流了。
- Java code
public static void main(String[] args) throws IOException { String dir = "D:/workspace/TestProject/src/com/io/ByteReadFileTest.java"; String src = "D:/workspace/TestProject/src/com/io/out.java"; InputStream input = new FileInputStream(dir); OutputStream out = new FileOutputStream(src); int length = 0; byte[] b = new byte[1024];// 缓冲区 while ((length = input.read(b)) != -1) { System.out.print(new String(b, 0, length)); out.write(b, 0, length);// 重要... out.flush(); } out.close(); }
------解决方案--------------------
while(in.hasNextLine()){ //你每次循环读入一行,进行转换,
line=in.nextLine(); //下一次循环的时候,前一行的信息就丢失了
所以,你应该把每次循环的结果保存到一个临时变量,最后把所有结果返回
即
- Java code
StringBuilder buf = new StringBuilder();while(in.hasNextLine()){ line=in.nextLine(); int count=0; while(count<line.length()){ char letter=line.charAt(count); if(letter>='a' && letter<'n') letter+=num; else if(letter>='n' && letter<='z') letter-=num; if(letter>='A' && letter<'N') letter+=num; else if(letter>='N' && letter<='Z') letter-=num; count++; buf.append(letter); //保留到临时变量 } buf.append("\n"); //追加换行符}return buf.toString();