使用FileWriter打印新行

时间:2013-11-27 07:10:05

标签: java

这是一种加密/解密文件的方法(SourceFile.txt)并将结果保存在另一个文件中(ConvertedFile.txt)

private void crypto(int index, int k)   throws IOException// 0 -> encrypt       1 -> decrypt
{
    FileReader in;
    FileWriter out;
    try
    {
        in = new FileReader("SourceFile.txt");
        out = new FileWriter("ConvertedFile.txt");
    }
    catch(FileNotFoundException e)
    {
        System.out.println("File NOT Found.");
        return;
    }
    c = new cipher(k);
    Scanner sc = new Scanner(in);
    String line,token;
    StringTokenizer st;
    while(sc.hasNextLine())
    {
        line = sc.nextLine();
        st = new StringTokenizer(line," ");
        while(st.hasMoreTokens())
        out.write(c.convert(st.nextToken(),index)+" ");
        out.write(10);
    }
    in.close();
    out.close();
}

如果sourceFile中有类似

的内容

玛丽

一点点

羊肉

convertedFile包含加密为

Qevc leh e pmxxpi peqf

我是否可以使用FileWriter在每一行的末尾打印'\ n'(新行)?

我甚至试过out.write(10)......没有用

4 个答案:

答案 0 :(得分:2)

使用PrintWriter

PrintWriter p = new PrintWriter(out);
p.println(str);

答案 1 :(得分:1)

你错过了while循环的大括号。

while(sc.hasNextLine())
{
    line = sc.nextLine();
    st = new StringTokenizer(line, " ");

    while(st.hasMoreTokens()) 
    {   // Add braces here for newline
        out.write(c.convert(st.nextToken(), index) + " ");
        out.write(10);  //Without braces it will be skipped.
    }
}

答案 2 :(得分:1)

您可以将FileWriter打包到BufferedWriter并使用newLine()

BufferedWriter bw = new BufferedWriter(new FileWriter("text.txt"));

bw.write(line);
bw.newLine();

答案 3 :(得分:0)

        FileWriter out = null;
        try {
            out = new FileWriter("F:/work1.txt");
            out.write("Rakesh");
            out.write("\r\n");
            out.write("KR");
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

然后该文件包含:

Rakesh
KR

或者您可以使用BufferedWriter作为

public void fileWrite(String fileName,ArrayList<String> str){
        File           f ;
        FileWriter     fw = null;
        BufferedWriter bw = null;
        try {
            f  = new File(fileName);
            fw = new FileWriter(f.getAbsoluteFile());
            bw = new BufferedWriter(fw);
            for(String i:str){
                bw.write(i);
                bw.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                if(bw!=null)
                    bw.close();
                if(fw!=null)
                    fw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }   
    }