2014-11-09 84 views
2

我有一個文件,裏面有數據。在我的主要方法中,我讀入文件並關閉文件。我調用另一種在原始文件的同一文件夾內創建新文件的方法。所以現在我有兩個文件,即原始文件和從我調用的方法創建的文件。我需要另一種方法從原始文件中獲取數據並將其寫入創建的新文件。我怎麼做?從一個文本文件中取出數據並將其移動到一個新的文本文件

import java.io.*; 
import java.util.Scanner; 
import java.util.*; 
import java.lang.*; 

public class alice { 

    public static void main(String[] args) throws FileNotFoundException { 
     String filename = ("/Users/DAndre/Desktop/Alice/wonder1.txt"); 
     File textFile = new File(filename); 
     Scanner in = new Scanner(textFile); 
     in.close(); 
     newFile(); 
    } 

    public static void newFile() { 
     final Formatter x; 
     try { 
      x = new Formatter("/Users/DAndre/Desktop/Alice/new1.text"); 
      System.out.println("you created a new file"); 
     } catch (Exception e) { 
      System.out.println("Did not work"); 
     } 
    } 

    private static void newData() { 
    } 

} 
+0

從文件中讀取一行,並使用'printstream'將其打印在另一個 – 2014-11-09 05:45:04

+0

它像一個故事,所以將它仍然工作一樣嗎? – unlimited4311 2014-11-09 05:46:57

回答

0

如果您的要求是將您的原始文件內容複製到新文件。那麼這可能是一個解決方案。

解決方案:

首先,讀給你的原始文件使用BufferedReader和內容傳遞到使用PrintWriter它創建新的文件的另一種方法。並將你的內容添加到你的新文件。

例子:

public class CopyFile { 

    public static void main(String[] args) throws FileNotFoundException, IOException { 
    String fileName = ("C:\\Users\\yubaraj\\Desktop\\wonder1.txt"); 
    BufferedReader br = new BufferedReader(new FileReader(fileName)); 
    try { 
     StringBuilder stringBuilder = new StringBuilder(); 
     String line = br.readLine(); 

     while (line != null) { 
      stringBuilder.append(line); 
      stringBuilder.append("\n"); 
      line = br.readLine(); 
     } 
     /** 
     * Pass original file content as string to another method which 
     * creates new file with same content. 
     */ 
     newFile(stringBuilder.toString()); 
    } finally { 
     br.close(); 
    } 

    } 

    public static void newFile(String fileContent) { 
    try { 
     String newFileLocation = "C:\\Users\\yubaraj\\Desktop\\new1.txt"; 
     PrintWriter writer = new PrintWriter(newFileLocation); 
     writer.write(fileContent);//Writes original file content into new file 
     writer.close(); 
     System.out.println("File Created"); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    } 
} 
+0

非常感謝你! – unlimited4311 2014-11-09 06:34:29

+0

@ unlimited4311不客氣! – Yubaraj 2014-11-09 06:42:27

+0

我還有一個問題,如果我有更多文件要寫入新文件,是否需要更改? – unlimited4311 2014-11-09 06:50:48

相關問題