『壹』 Java 如何把數據保存到TXT文件,
首先,打開一個txt文件,File
file
=
new
File("文件路徑");
然後,封裝輸出流,DataOutputStream
os
=
new
DataOutputStream(new
FileOutputStream(file));
接著,往os裡面寫數據,os.writeInt(...)
os.writeByte(...)
os.writeChar(...)等等,你要寫什麼樣類型的數據,就調用什麼樣類型的方法。
最後,記得關掉輸出流,調用os.close()
『貳』 Java中如何通過txt文件存儲和取出數據
Java中讀取txt文件可以使用file類先創建一個對象,然後使用I/O操作,進行讀取或者寫入操作,示例如下:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class demo2 {
private static String path = "f:/demo1.txt";
private static File file;
static{
file = new File(path);
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws IOException {
Student stu = new Student(1,"張三",90);
writeDataToFile(file,stu);
readDataFromFile(file);
}
private static void readDataFromFile(File file) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String str = "";
while((str = reader.readLine())!=null){
String[] stuInfo = str.split(",");
System.out.println("學號:"+stuInfo[0]+" 姓名:"+stuInfo[1]+" score:"+stuInfo[2]);
}
}
private static void writeDataToFile(File file,Student stu) throws FileNotFoundException {
PrintWriter out = new PrintWriter(new FileOutputStream(file, true));
out.println(stu.toString());
out.close();
}
}
『叄』 怎麼用java儲存文件(save file)
java.io底下有很多類可以寫文件,FileOutStream,RandomAccessFile之類的都行。
『肆』 java怎麼保存文件
可以使用java.io.FileOutputStream流保存任意文件或者用java.io.ObjectOutputStream流保存類文件
『伍』 java怎麼將一些文字存儲到硬碟文件中
Java是通過使用I/O文件操作類,創建輸入輸出流,將數據保存在指定的路徑下的文件裡面。
示例代碼:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class WriteFileTest {
public static void main(String[] args) {
FileOutputStream fop = null;
File file;
String content = "This is the text content";
try {
file = new File("D:/test.txt");//初始化file
fop = new FileOutputStream(file);//初始化輸出流
// 若文件不存在,則創建它
if (!file.exists()) {
file.createNewFile();
}
// 獲取位元組的內容數組
byte[] contentInBytes = content.getBytes();
fop.write(contentInBytes);//寫出到指定路徑文件中位元組的內容數組
fop.flush();
fop.close();
System.out.println("Done");
} catch (IOException e) { //捕捉異常
e.printStackTrace();
} finally {
try {
if (fop != null) {
fop.close();
}
} catch (IOException e) { //捕捉異常
e.printStackTrace();
}
}
}
}
『陸』 java怎麼存取文本數據
存數據:
首先,打開一個txt文件,File file = new File("文件路徑");
然後,封裝輸出流,DataOutputStream os = new DataOutputStream(new FileOutputStream(file));
接著,往os裡面寫數據,os.writeInt(...) os.writeByte(...) os.writeChar(...)等等,你要寫什麼樣類型的數據,就調用什麼樣類型的方法。
最後,記得關掉輸出流,調用os.close()。
取數據:
java讀取txt文件內容。可以作如下理解:
首先獲得一個文件句柄。File file = new File(); file即為文件句柄。兩人之間連通電話網路了。接下來可以開始打電話了。
通過這條線路讀取甲方的信息:new FileInputStream(file) 目前這個信息已經讀進來內存當中了。接下來需要解讀成乙方可以理解的東西
既然你使用了FileInputStream()。那麼對應的需要使用InputStreamReader()這個方法進行解讀剛才裝進來內存當中的數據
解讀完成後要輸出呀。那當然要轉換成IO可以識別的數據呀。那就需要調用位元組碼讀取的方法BufferedReader()。同時使用bufferedReader()的readline()方法讀取txt文件中的每一行數據哈。
『柒』 java如何保存文件
這是我原來做的例子,裡面有文件儲存的內容,代碼不多,給你參考參考.
/**
* 五個按鈕的故事,西西哈。
*/
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class FileMessage extends Frame implements ActionListener
{
private static final long serialVersionUID = 10L;
Dialog dia;
private Panel p;
private File fi;
Process po=null;
private String s;
private TextArea ta;
private FileDialog fd;
private Button b1,b2,b3,b4,b5;
private Button b6;
public FileMessage()
{
super("文本文件處理");
setBackground( Color.LIGHT_GRAY );
setLocation(200,300);
setResizable( false);
setVisible( true);
addWindowListener( new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit( 0);
}
});
}
public void init()
{
ta=new TextArea("\n\n\n\n\n\t\t\t\t文本顯示區");
ta.setSize(30,5);
ta.setEditable(false);
add( ta,"North");
p=new Panel();
add( p,"Center");
b1=new Button("瀏覽");
b2=new Button("保存");
b3=new Button("清空");
b4=new Button("關閉");
b5=new Button("獨立打開");
b6=new Button("確定");
p.add(b1);
p.add(b2);
p.add(b3);
p.add(b4);
p.add(b5);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
b6.addActionListener(this);
fd=new FileDialog(this,"請選擇文件",FileDialog.LOAD);
fd.setDirectory("f:\\note");
pack();
dia=new Dialog(this,"注意",true);
dia.setLayout(new BorderLayout());
Panel p1=new Panel();
p1.add( b6);
dia.add(new Label(" 請先選擇文件"),BorderLayout.CENTER);
dia.add( p1,BorderLayout.SOUTH);
dia.addWindowListener( new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
dia.setVisible( false);
}
});
dia.setLocation(310,370);
dia.setSize(200,130);
}
public static void main(String[] args)
{
new FileMessage().init();
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b1)
{
fd.setVisible(true);
s=fd.getDirectory()+fd.getFile();
fi=new File(s);
byte[] b=new byte[(int)fi.length()];
try
{
new FileInputStream(fi).read(b);
ta.setText(new String(b,0,(int)fi.length()));
}
catch(Exception e1){}
ta.setEditable(true);
}
else if(e.getSource()==b2)
{
try
{
if(ta.getText().equals("保存成功")||ta.getText() .equals( ""))
{}
else
{
new FileOutputStream(fi).write(ta.getText().getBytes());
ta.setText("保存成功");
ta.setEditable(false);
}
}
catch(FileNotFoundException e1)
{
ta.setText(e1.getMessage());
}
catch(IOException e1)
{
ta.setText("出現IOException異常");
}
}
else if(e.getSource()==b4)
System.exit(0);
else if(e.getSource()==b3)
{
ta.setText("");
ta.setEditable( false);
}
else if(e.getSource()==b5)
{
if(s==null)
{
dia.setVisible(true);
}
else
{
try
{
po=Runtime.getRuntime().exec("notepad.exe "+s);
}
catch(Exception ei)
{}
}
}
else if(e.getSource() ==b6)
{
dia.setVisible(false);
}
}
}
『捌』 Java中通過txt文件存儲和取出數據
如果是這樣的話,你就先用string的split方法以,為分隔符號分開,再replace「」,這兩個東東就可以得到你要的中間的數據了。有個缺點比較佔用內存,或許你也可以去讀文件讀到,的時候就將之前的存起來,然後再讀下面的東西。思路而已試試看吧~
『玖』 java程序中怎樣用文件存儲數據
對於一些小文件,我們可以一次性讀取它的所有位元組,然後一次提交到資料庫
///
/// 這個方法演示了如何一次提交所有的位元組。這樣導致的結果是:應用程序立即需要申請等同於文件大小的內存
static void SubmitFileByOnce() {
string file = @"F:\功夫熊貓.rmvb";//文件大小為519MB
byte[] buffer = File.ReadAllBytes(file);
using (SqlConnection conn = new SqlConnection("server=(local);database=demo;integrated security=true")) {
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "INSERT INTO Files(FileName,FileContents) VALUES(@fileName,@fileContents)";
cmd.Parameters.AddRange(
new[]
{
new SqlParameter("@fileName",file),
new SqlParameter("@fileContents",buffer)
});
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
但是,上面的方法有幾個問題,主要體現在如果文件比較大的話
它需要一次性很大的內存,具體數據等同於文件大小。因為File.ReadAllBytes方法是將所有位元組全部讀入到內存。
它會導致提交失敗,就是因為數據太大了。資料庫也會拒絕。
那麼,我就對這個方法做了一下改進,將文件拆分為5MB一段,也就是說,此時每次申請的內存只有5MB。這就大大地提高了可用性。
/// 這個方法是將文件切分為5MB的塊,每次只是提交5MB,所以可能多次提交,但內存佔用就比較小
static void SubmitFileStepByStep() {
string file = @"F:\功夫熊貓.rmvb";//以這個文件為例,大小為519MB,一共需要的時間大約94秒。還是有點慢的,所以還可能需要進行壓縮
FileStream fs = new FileStream(file, FileMode.Open);
byte[] buffer = new byte[5 * 1024 * 1024];
int readCount;
using (SqlConnection conn = new SqlConnection("server=(local);database=demo;integrated security=true"))
{
conn.Open();
while ((readCount = fs.Read(buffer, 0, buffer.Length)) > 0)
{
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "INSERT INTO Files(FileName,FileContents) VALUES(@fileName,@fileContents)";
cmd.Parameters.AddRange(
new[]
{
new SqlParameter("@fileName",file),
new SqlParameter("@fileContents",buffer)
});
cmd.ExecuteNonQuery();
}
}
conn.Close();
}
}
這樣的話,有一個後果就是一個文件,可能在資料庫中會有多條記錄。所以在讀取的時候,我們需要對其進行合並
static void DownloadFile() {
string file = @"F:\功夫熊貓.rmvb";
string destfile = @"E:\Temp\Temp.wmv";
using (SqlConnection conn = new SqlConnection("server=(local);database=demo;integrated security=true"))
{
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT FileContents FROM Files WHERE FileName=@fileName";
cmd.Parameters.AddRange(
new[]
{
new SqlParameter("@fileName",file),
});
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
FileStream fs = new FileStream(destfile, FileMode.Append, FileAccess.Write);
while (reader.Read())
{
byte[] buffer = (byte[])reader[0];
fs.Write(buffer, 0, buffer.Length);
}
fs.Close();
reader.Close();
conn.Close();
}
}
}