I'm trying to write some numbers into a *.txt file, using write.write() function. When I open the created file with notepad I see gibberish, but when I open with notepad++, the file is ok. Can anyone explain why is this happening?
try {
for(int i = 0; i < predictionsList.size(); i ++){
writer.write(Integer.toString(predictionsList.get(i)));
writer.write("\n");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The information you provide in the question is not enough, even though we can infer that your issue is related with the encoding of the text file you are writing
Verify the BOM format, that is by default selected in notepad++
Related
I have been experimenting with writing to text files for output instead of System.out.println(). When I try this, though, nothing seems to be written. What is the issue with my code?
try{
List<String> lines = Arrays.asList("Data Goes Here");
Path file = Paths.get("output.txt");
Files.write(file, lines, Charset.forName("UTF-8"));
}
catch (IOException ex) {
System.out.println("Frick, something broke. Sorry folks, go home.");
}
I just did a small change to your code by passing the path as the resources directory located in the root of my project. I was able to write to the file successfully.
Here is the updated code:
try {
List<String> lines = Arrays.asList("Data Goes Here");
Path file = Paths.get("./resources/test.txt");
Files.write(file, lines, Charset.forName("UTF-8"));
}
catch (IOException ex) {
ex.printStackTrace();
System.out.println("Frick, something broke. Sorry folks, go home.");
}
I want to print my console lines to txt file.I want this operation in else statement.But it writes to file only last record.How can i fixed it? When i try buffered reader it cant solve my problem.Thanks everybody.Have a good day.Which solution do you advice to me?
for(int iy=0;iy<arr.length;iy++){
if( arr[iy].contains("•") || arr[iy].contains("Contact") || arr[iy].contains("#") || arr[iy].contains("Activities and Societies") || arr[iy].contains("Page")){
}
else if(arr[iy].contains("Summary")){
//System.out.println(arr[iy]+"enes");
while(exit==false){
iy++;
if(arr[iy].contains("Experience")){
exit=true;
}
}
}
else if(arr[iy].contains("Skills") || arr[iy].contains("Languages")){
while(exit==false){
iy++;
if(arr[iy].contains("Education")){
exit=true;
}
}
}
else
{
System.out.println(arr[iy]);
try(PrintWriter bw = new PrintWriter(new FileWriter(FILENAME2))){
bw.write(arr[iy]);
//out.newLine();
bw.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Your code is very convoluted, but the reason for just the last line being written is clear - you open the file for each line you are about to output to it, and overwrite the previous contents of the file.
You shouldn't open and close the file for each line. Open it once before the loop, and close it after the loop.
If it did make sense to open and close the file multiple times, you should have opened the FileWriter in append mode (by using new FileWriter(FILENAME2,true)).
Looks like you're re-creating the PrintWriter at every step of the loop, which overwrites the file. Create it before the loop and close it afterwards.
I tried to open from the normal eclipse it worked fine, but when exported same file to a jar
its giving an error.
Can anyone help?
public void mouseClicked(MouseEvent e) {
Process process;
try {
String resourceLocation = MainPanel.class.getProtectionDomain().getCodeSource().getLocation().getPath();
resourceLocation += "/com/microsoftplatformready/resources/images/endUserLicenseAgreement.docx";
process = Runtime.getRuntime().exec("soffice -reader "+resourceLocation);
process.waitFor();
process.destroy();
} catch (Exception e1) {
e1.printStackTrace();
}
}
Please help
Thanks
As Joop Eggen already said in the comment, first create a new temp file and copy your actual document to the temp file and open this one instead.
The reason is simply, Openoffice can't read files stored in an archive.
Path temp = Files.createTempFile("prefix", "suffix.ext");
Files.copy(getClass().getResourceAsStream(resourceLocation), temp);
process = Runtime.getRuntime().exec("soffice -reader "+ temp.toAbsolutePath().toString())
Argargarg.
I am trying to get information from a user input, then to write it to a system file. I get the input, and I call getBytes on it. It logs to the file something along the lines of "null" and random numbers after that. I tried getting it to a string, no luck there, it was a random chain of symbols
Here is the specific code:
TextView note_input=(TextView) findViewById(R.id.note_input);
FileOutputStream fos=null;
String newNote=note_input.getText().toString();
Log.w("Debug",newNote);
try {
fos=openFileOutput("currentNote",Context.MODE_APPEND);
} catch (FileNotFoundException e) {
//IT_SHOUD_NOT_EXIST
}
try {
Log.w("Debug",newNote.getBytes().toString());
fos.write(newNote.getBytes());
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I appreciate any help!
String.getBytes returns array of bytes, and when you try to do toString() you are actually writing it's pointer to string. You already have String change this line
Log.w("Debug",newNote.getBytes().toString());
into
Log.w("Debug",newNote);
and you will have proper Log output, and File should be written properly already.
Hope this helps and enjoy your work
Just a shot in the dark, but I notice you're calling getBytes() without specifying the character encoding. Unless your output file is the same character encoding as the system default encoding, you could easily get gibberish on the output.
I'm trying to export data into a CSV file through Java and I've got some code to do it but it doesn't seem to be outputting the CSV file. Could someone tell me what's wrong? What I would like to do is rather than saving the file somewhere, I would like it to be directly exported to the user.
EDIT: Just in case it's not clear, I don't want the file to be saved anywhere but would like it to be outputted automatically to the user i.e. they click export and get the "Run/Save results.csv" window and they open the file. Currently the file is getting saved so I know that the method seems to work, just in the opposite way that I want it to.
public static void writeToCSV(List<Map> objectList) {
String CSV_SEPARATOR = ",";
try {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("results.csv"), "UTF-8"));
for (Map objectDetails : objectList) {
StringBuffer oneLine = new StringBuffer();
Iterator it = objectDetails.values().iterator();
while (it.hasNext()) {
Object value = it.next();
if(value !=null){
oneLine.append(value.toString());
}
if (it.hasNext()) {
oneLine.append(CSV_SEPARATOR);
}
}
bw.write(oneLine.toString());
bw.newLine();
}
bw.flush();
bw.close();
} catch (UnsupportedEncodingException e) {
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
I would recommend using a framework like opencsv for that. It also does escaping and quoting for you.
If you're not getting errors, check the directory where your code is. Without a specific path, your file is being saved there.
EDIT: Since the file is being saved and you want it to open automatically, use
Runtime.getRuntime().exec("results.csv");
(For Windows - opens the csv file in the default application for csv files)
Runtime.getRuntime().exec("open results.csv");
(For Mac - opens the csv file in the default application for csv files)
recommend HSSFWorkbook to easily read and write excel files.
http://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFWorkbook.html
To do that, the CSV reader need to read the memory of your program. This is a little complex thing to do. So, save the file in a temp folder instead. There is no problem to do this sort of thing.