Rename a file using Java

前端 未结 14 828
感情败类
感情败类 2020-11-22 07:54

Can we rename a file say test.txt to test1.txt ?

If test1.txt exists will it rename ?

How do I rename it to the alrea

14条回答
  •  失恋的感觉
    2020-11-22 08:07

    Running code is here.

    private static void renameFile(File fileName) {
    
        FileOutputStream fileOutputStream =null;
    
        BufferedReader br = null;
        FileReader fr = null;
    
        String newFileName = "yourNewFileName"
    
        try {
            fileOutputStream = new FileOutputStream(newFileName);
    
            fr = new FileReader(fileName);
            br = new BufferedReader(fr);
    
            String sCurrentLine;
    
            while ((sCurrentLine = br.readLine()) != null) {
                fileOutputStream.write(("\n"+sCurrentLine).getBytes());
            }
    
            fileOutputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileOutputStream.close();
                if (br != null)
                    br.close();
    
                if (fr != null)
                    fr.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
    

提交回复
热议问题