2014-01-14 1 views
-1

Я нахожу некоторые трудности с этим вопросом, поскольку я только начал с программирования Java. Я искал в Интернете, но я нашел только соответствующие ответы на C++ и php. Но я не знаю, если эти ответы также применимы к яве BufferedReaders или PrintWriters ...Как вы можете создать объект PrintWriter или BufferedReader, соответствующий файлу на вашем компьютере?

ответ

0
FileReader in = new FileReader("C:/test.txt"); 
BufferedReader br = new BufferedReader(in); 
0
package xbn.io; 
    import java.io.FileWriter; 
    import java.io.BufferedWriter; 
    import java.io.PrintWriter; 
    import java.io.IOException; 
    import java.io.FileNotFoundException; 
public class PrintWriterToFileTest { 
    public static final void main(String[] as_1RqdPathToFile) { 
     PrintWriter pw = null; 
     try { 
           //true, true: Append, auto-flush 
     pw = (new PrintWriter(new BufferedWriter(new FileWriter("temp.txt", true)), true)); 

     //The PrintWriter was successfully created. 

     } catch(FileNotFoundException fnfx) { 
     throw new RuntimeException(sIOXPRE + s_path + "\"", fnfx); 
     } catch(IOException iox) { 
     throw new RuntimeException(sIOXPRE + s_path + "\"", iox); 
     } 

     pw.write("Hello!"); 
     pw.close();  //Must close, or text is not auto-flushed! 
    } 
     private static String sIOXPRE = "s_path must point to a write-ABLE file (the directory must exist, but the file need not exist). s_path=\""; 
} 

Я написал строитель-класс, который является удобным способом создания PrintWriters, что запись в файл ,

https://gist.github.com/aliteralmind/8419153

Вот пример использования:

String sPath = "C:\\temp\\temp.txt"; 
PrintWriter pwf = null; 
try { 

    pwf = new NewPrintWriterForFile(). 
     append().autoFlush(). 
     build(sPath); 

} catch(RuntimeException rtx) { 
    throw new IllegalArgumentException("Path invalid? sPath=\"" + sPath + "\""); 
} 

pwf.write("Hello"); 
pwf.close();   //Must close, or the text is not flushed! 

System.out.println("Text written to \"" + sPath + "\""); 
0

вы также можете:

File file = new File("C:/Users/Me/Desktop/directory/file.txt"); 
file.getParentFile().mkdirs(); 

PrintWriter printWriter = new PrintWriter(file);