所以我在Java中每天都在學習新的東西,並且我希望有一天我會在Java中擁有和PHP相同的知識。像PHP一樣的文件寫入/讀取功能
我試圖做一個類,它是類似於fopen
,fwrite
,fclose
在PHP中,如:
<?php
$fp = fopen('data.txt', 'w');
fwrite($fp, '1');
fwrite($fp, '23');
fclose($fp);
// the content of 'data.txt' is now 123 and not 23!
?>
我也需要寫
Ø的方法 - 進行刪除和寫/覆蓋
a - 用於追加末尾
和一個讀取函數,它會逐行返回內容,所以我可以把它放到一個數組中,如file_get_contents(file);
這是我迄今爲止...
import java.io.*;
import java.util.Scanner;
/**
Read and write a file using an explicit encoding.
Removing the encoding from this code will simply cause the
system's default encoding to be used instead.
**/
public final class readwrite_txt
{
/** Requires two arguments - the file name, and the encoding to use. **/
public static void main(String[] args) throws IOException
{
String fileName = "text.txt";
String encoding = "UTF-8";
readwrite_txt test = new readwrite_txt(fileName,encoding);
test.write("argument.txt","some text","UTF-8","o");
}
/** Constructor. **/
readwrite_txt(String fileName, String encoding)
{
String fEncoding = "text.txt";
String fFileName = "UTF-8";
}
/** Write fixed content to the given file. **/
public void write(String fileName,String input,String encoding,String writeMethod) throws IOException
{
// Method overwrite
if(writeMethod == "o")
{
log("Writing to file named " + fileName + ". Encoding: " + encoding);
Writer out = new OutputStreamWriter(new FileOutputStream(fileName), encoding);
try
{
out.write(input);
}
finally
{
out.close();
}
}
}
/** Read the contents of the given file. **/
public void read(String fileName,String output,String encoding,String outputMethod) throws IOException
{
log("Reading from file.");
StringBuilder text = new StringBuilder();
String NL = System.getProperty("line.separator");
Scanner scanner = new Scanner(new FileInputStream(fileName), encoding);
try
{
while (scanner.hasNextLine())
{
text.append(scanner.nextLine() + NL);
}
}
finally
{
scanner.close();
}
log("Text read in: " + text);
}
// Why write System.out... when you can make a function like log("message"); simple!
private void log(String aMessage)
{
System.out.println(aMessage);
}
}
也,我不明白爲什麼我必須
readwrite_txt test = new readwrite_txt(fileName,encoding);
,而不是
readwrite_txt test = new readwrite_txt();
我只是想要有一個類似於PHP的簡單函數。
EDITED
所以我的函數必須是
$fp = fopen('data.txt', 'w'); ==> readwrite_txt test = new readwrite_txt(filename,encoding,writeMethod);
fwrite($fp, '23'); ==> test.write("the text");
fclose($fp); ==> ???
的作品,但我必須使它像一個功能,它可能會返回一個數組,這個想法是,一切必須是有序的,優雅... – Master345 2012-01-04 19:40:24
返回,您可以使用字符串的ArrayList的數組,你可以請閱讀有關該課程的更多信息:http://javarevisited.blogspot.com/2011/05/example-of-arraylist-in-java-tutorial.html。您應該將緩衝區中的所有行添加到此ArrayList並返回ArrayList。如果你使用Java,忘記簡單的功能,所有的東西都應該是一個類的一部分。這有很多的好處,也有很多缺點。 – 2012-01-04 19:44:52
所以你的問題是在返回數組? 的ArrayList將解決您的肯定 問題,這是因爲它 'ArrayList的陣列=新的ArrayList ()僞代碼; array.add(「1」); array.add(「2」); array.clear();' –
mhyassin
2012-01-04 19:50:34