[英]How to save file and read
我創建了一個程序,以網格布局格式放置隨機圖像。 網格布局的大小為6 x 6 =36。只有10張圖像被填充(每個圖像都不同),其余為空。
替代文字http://freeimagehosting.net/uploads/bfb7e85f63.jpg
如何將其保存到文件中並再次讀取,這樣它將在網格上以相同的位置顯示相同的圖像?
這是我用來保存圖像的代碼:
//image file
String []arrPic = {"pic1.jpg","pic2.jpg","pic3.jpg","pic4.jpg","pic5.jpg","pic6.jpg","pic7.jpg","pic8.jpg","pic9.jpg","pic10.jpg",,"pic11.jpg","pic12.jpg","pic13.jpg"};
ArrayList<String> pictures = new ArrayList<String>(Arrays.asList(arrPic));
ArrayList<String> file = new ArrayList<String>();
JPanel pDraw = new JPanel(new GridLayout(6,6,2,2));
...
//fill all grids with empty label
for (int i =0; i<(6*6); i++){
JLabel lbl = new JLabel("");
pDraw.add(lbl);
}
...
//Choose random box to be filled with images
for(int i=0; i<10; i++){
Boolean number = true;
while(number){
int n = rand.nextInt(35);
if(!(arraylist.contains(n)))
number = false;
arraylist.add(n);
}
//fill the grids with images
for(int i=0; i<arraylist.size(); i++){
//select random image from arraylist
int index = rand.nextInt (pictures.size());
String fileName = (String) pictures.get(index );
//find the image file
icon = createImageIcon(fileName);
//save the file in a new file
file.add(fileName);
//rescaled the image
int x = rand.nextInt(50)+50;
int y = rand.nextInt(50)+50;
Image image = icon.getImage().getScaledInstance(x,y,Image.SCALE_SMOOTH);
icon.setImage(image);
//remove empty label and replace it with an image
int one = (Integer) arraylist.get(i);
pDraw.remove(one);
final JLabel label;
pDraw.add(label,one);
}
在您的代碼中,類rand
是java.util.Random
嗎? 如果是這樣,您可以自己“播種”它,然后將種子值保存到文本文件中。 對於任何給定的種子,(偽)隨機數生成器將以相同順序產生相同的“隨機”數。 所以:
Random rand = null;
然后,創建一個新的“種子”並將其保存到文件中:
long seed = System.currentTimeMillis();
rand = new Random(seed);
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("whatever.txt"));
writer.write(Long.toString(seed));
writer.close();
} catch(IOException e) {
e.printStackTrace();
}
或讀回以前保存的值:
long seed = 0;
try {
BufferedReader reader = new BufferedReader(new FileReader("whatever.txt"));
seed = Long.parseLong(reader.readLine());
reader.close();
} catch(IOException e) {
e.printStackTrace();
}
rand = new Random(seed);
請注意,此代碼不會檢查以確保文件已退出,或者文件不為空,或者文件中除了有效數字之外不包含其他內容,等等。
糟糕,誤解了您的問題。
我會將每個網格值鏈接到指定圖片/文件的數組的索引。 保存該設置后,保存一個新數組,並使用與網格關聯的值(其中26個應為null,對嗎?)。最初打開文件時,如果數組完全為空,則從數組中讀取程序。 。
-為網格創建一個foreach循環,如果它們為空,則將數組值設置為null,否則將值設置為與之關聯的圖像。 使用pdraw.checkImage();
好了,您必須保存一個配置文件以及所有需要的信息。 您可能會使用屬性文件。 因此,您可以遍歷網格,每次找到包含圖像的單元格時,便會保存索引和文件名。 然后,當您重新加載程序時,您將遍歷所有可能的屬性值以查找存在的屬性值,然后獲取圖像的文件名,讀取圖像並將其加載到單元格中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.