有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

用Java将字符串复制到文件开头

我想在文件开头写一个字符串,我该怎么做

我根本不知道如何添加字符串。。这就是我目前所做的:

  public static void prepend (String filename, String data) throws IOException{

    FileOutputStream file= new FileOutputStream(filename);

}

(i)write()方法只接受字节——我应该怎么做才能在我的情况下使用它

(ii)-如何将字符串复制到文件开头

而且——如果有人知道一个网站,它有所有的作者/读者,以及所有这些经过精心安排和解释的信息流——我会非常感激,我快疯了

谢谢


共 (2) 个答案

  1. # 1 楼答案

    下面是运行代码

    私有静态void addHeader(文件名){

        FileOutputStream fileOutputStream =null;
    
        BufferedReader br = null;
        FileReader fr = null;
        String newFileName = fileName.getAbsolutePath() + "@";
    
        try {
    
            fileOutputStream = new FileOutputStream(newFileName);
            fileOutputStream.write("yourCopiedDataHere".getBytes());
    
            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();
    
                System.out.println(fileName+" is deleted "+ fileName.delete());
                new File(newFileName).renameTo(new File(newFileName.replace("@", "")));
    
    
            } catch (IOException ex) {
    
                ex.printStackTrace();
    
            }
    
        }
    
    }
    
  2. # 2 楼答案

    您可以使用缓冲写入程序,即

    // read the existing contents of the file into a string builder   
    BufferedReader is = new BufferedReader
        (new InputStreamReader(new FileInputStream(filename)));
    
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = is.readLine()) != null) {
        sb.append(line);
    }
    
    // open the file for writing
    BufferedWriter s = new BufferedWriter
        (new OutputStreamWriter(new FileOutputStream(filename)));
    
    // prepend your text
    s.writeLine("some line of text to prepend");
    
    // rewrite the file contents
    s.writeLine(sb.toString());