This question already has answers here:
How do I create a file and write to it?
(35 answers)
Closed 6 years ago.
I have a HashMap that I would like to write as separate lines to a text file. How do you go about doing this? In the SysOut above the code for writing to a text file I am printing out the values in the way that I would like to print them.
map.forEach((k,v)-> System.out.println(k+", "+v));
File file = new File(Constants.FILEPATH);
FileOutputStream f = new FileOutputStream(file);
ObjectOutputStream s = new ObjectOutputStream(f);
s.writeObject(map);
s.close();
Don't use an ObjectOutputStream, use a PrintWriter:
try (PrintWriter out = new PrintWriter(file)) {
map.forEach((k,v) -> out.println(k+", "+v));
}
Related
This question already has answers here:
Write chinese characters from one file to another
(2 answers)
Closed 7 years ago.
copying Chinese file in java using this code . but the destination file contains question mark (?) instead of Chinese character . is there any way in java to achieve this functionality..
File source = new File("H:\\work-temp\\file");
File dest = new File("H:\\work-temp\\file2");
try {
FileUtils.copyDirectory(source, dest);
} catch (IOException e) {
e.printStackTrace();
}
First of all, while copying a file, the destination should be a folder not file... so please change File dest = new File("H:\\work-temp\\file2"); to File dest = new File("H:\\work-temp");
Next you should use FileUtils.copyFile(source, dest); instead FileUtils.copyDirectory(source, dest);
Use one of the JDK 7 Files.copy methods. They create a binary copy of your file.
You are miss the extension of files for ex: file.txt and file2.txt:
File source = new File("H:\\work-temp\\file.txt");
File dest = new File("H:\\work-temp\\file2.txt");
For coping use this:
FileChannel inputChannel = null;
FileChannel outputChannel = null;
try{
inputChannel = new FileInputStream(source).getChannel();
outputChannel = new FileOutputStream(dest).getChannel();
outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
} finally {
inputChannel.close();
outputChannel.close();
}
For more info go to this link
This question already has answers here:
Reading InputStream as UTF-8
(4 answers)
Closed 8 years ago.
I'm trying to get data from a text file, that was generated by ArcGIS, to clean it up using regex.
When I launch application by using RUN PROJECT, everything works, but when I launch the .jar file, it adds "Ā" symbol into the data.
Using NetBeans, JDK7, project encoding is set to UTF-8.
Here's the original string:
0,RIX_P_1,AREA,2,LGS,WGS84,TREE,32.3, , , ,25,0.61,M,90%,0.01, ,0.15,90%,0.1,EGM96,ESSENTIAL,08.11.2013,M, , ,NIL,NIL,METRUM,0.000000000000000,0.000000000000000,0.000000000000000,0.000000000000000,0.000000000000000,0.000000000000000,0.000000000000000,0.000000000000000,0,0,0,0,0,0,1,0,0, , , , , , , , , , , ,tree,**"23° 57' 51,805"" E","56° 53' 30,142"" N"
The program reads it like this (I replaced the middle part of the string with (===), it is unchanged):
0,RIX_P_1,AREA,2,(===),"23Ā° 57' 51,805"" E","56Ā° 53' 30,142"" N"
Here's the button code that does the reading job. It is partially taken from a tutorial:
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
int returnVal = fileChooser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try {
FileInputStream fis = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
jTextArea1.read( br, null );
} catch (IOException ex) {
System.out.println("problem accessing file"+file.getAbsolutePath());
}
} else {
System.out.println("File access cancelled by user.");
}
}
I found some information on the WEB it seems that problem is in encoding, but I cannot figure out, how to setup things correctly.
P.S. I'm a novice in programming, so excuse me for stupid questions :)
Although you have solved your problem, I suggest taking a look at Scanner class. It's much easier to use than all the Reader classes you are using.
This question already has answers here:
How to save a BufferedImage as a File
(6 answers)
Closed 8 years ago.
I saw many examples on the internet on how to convert a File into a BufferedImage, but I need to make a counter conversion.
I've tried some ways, but all are quite complicated.
I wonder if there is a direct way to accomplish this.
I have this in my code:
for (FileItem item : formItems) {
// processes only fields that are not form fields
if (!item.isFormField()) {
Date date = new Date();
String fileName = new File(item.getName()).getName();
String filePath = uploadPath + date.getTime() + fileName + ".tmp";
File storeFile = new File(filePath);
BufferedImage tempImg = ImageIO.read(storeFile);
//I make process in the tempImg
//I need save it
item.write(tempImg);
}
}
I don't need write a FileItem, but the BufferedImage that I have processed.
File outputfile = new File("image.jpg");
ImageIO.write(bufferedImage, "jpg", outputfile);
Is this what you are looking for?
This question already has answers here:
Copying files from one directory to another in Java
(34 answers)
Closed 9 years ago.
I want to copy a zip file from one folder to another folder in java.
i have a migrate.zip file in sourcefolder .i need to copy that migrat.zip file to destination
folder.
can any one help me on this.
Thanks&Regards,
sivakrishna.m
apache-commons-io library is helpful in you problem
org.apache.commons.io.FileUtils.copyFile(File, File)
FileUtils.copyFile(new File("/sourcefolder/migrate.zip"),
new File("/destination/migrate.zip"))
Please check the below question and answer. This may help you.
Best Way to copy a Zip File via Java
try this set of lines.
String sourceFilePath =" Source path";
File f = new File(sourceFilePath);
File f1 = new File(destinationFilePath);
File fCopy = new File(destinationFilePath);
if (f1.exists()) {
// Don't do anything..
f1.delete();
}
FileUtils.copyFile(f, fCopy)
Use java.util.ZipInputStream class to read migrate.zip file from source folder and use java.util.ZipOutputStream class to write migrate.zip to the destination folder....
public class CopyZip
{
public static void main(String[] args)
{
FileInputStream fin = new FileInputStream(new File("source_folder\migrate.zip"));
ZipInputStream zin = new ZipInputStream(fin);
byte[] in_bytes = new bytes[1000];
zin.read(in_bytes,0,1000);
FileOutputStream fout = new FileOutputStream(new File("dest_folder\migrate.zip"));
ZipOutputSrream zout = new ZipOutputStream(fout);
zout.write(in_bytes,0,in_bytes.length);
}
}
This question already has answers here:
Java FileWriter with append mode
(4 answers)
Closed 9 years ago.
I have created a Java Game and when the game finishes, a method is executed that tells the user to enter his his/her name then their score will save in playscores.txt document. This is working fine. However, i want the more than just one person's score in this document. I want it so everyone that plays the game name and score will be saved in this document. Would really appreciate some help.
This is my gameComplete Method code:
public void gameComplete() throws IOException {
String name = (String) JOptionPane.showInputDialog(
frame,
"Enter your name: ",
"Save Score",
JOptionPane.PLAIN_MESSAGE);
Score score = new Score(player.getScore(), name);
FileWriter fstream = new FileWriter("playerscores.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write("Name : " + score.getName() + System.getProperty( "line.separator" ) );
out.write("Score : " + score.getScore());
out.close();
}
I have tried different stuff, such as Objectoutputstream but unfortunately cannot figure out how to do it and was wondering if it is even possible. Furthermore, i would like to know what Class i should be using to get this done.
If you're happy to just append the new score to the end of the file, replace:
FileWriter fstream = new FileWriter("playerscores.txt");
with:
FileWriter fstream = new FileWriter("playerscores.txt", true);
If you can have more than one user playing at the same time, you'll need to use file locking too, to avoid race conditions when accessing the file.
In order to do it for more than one person, you should open the file in append mode.
FileWriter fstream = new FileWriter("playerscores.txt",true);
Syntax: public FileWriter(File file, boolean append)
Parameters:
file - a File object to write to
append - if true, then bytes will be written to the end of the file
rather than the beginning.
By default, the append parameter is false. So , earlier, you were over-writing the score of the previous player with the current one.
Firstly, if you want the file to be added to rather than wiped and written to each time then make sure you add the second argument of true to have it append the text.
You could use a CSV file to store the answers in columns and then read them out parsing the data by using commas.
FileWriter fileW = new FileWriter("playerscores.txt", true);
Hope that helps.