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.
Related
I have one application that fills a JComboBox with the content of a text file (.db precisely). Everything works fine on IDE, however when creating a .jar nothing show on the JComboBox.
The code is as following:
private void fill(String type) throws FileNotFoundException {
BufferedReader input = null; // used to read file content
try {
input = new BufferedReader(new FileReader("pack"+ File.separator +type+".db")); // loading the file based on previous box (see image).
} catch (FileNotFoundException ex) {
Logger.getLogger(Calc.class.getName()).log(Level.SEVERE, null, ex);
}
try {
String line = null;
while (( line = input.readLine()) != null){
type_list.addItem(line); // adding to my JComboBox
}
input.close();`
As stated everything works fine on netbeans IDE and I get the following
IDE
However on .jar I get the following:
JAR
I tried reading the file from inputStream, with no success. I'm compiling the .db files with my application, but it's not mandatory for me (I can have .jar+ db files separately).
Thank you!!!
--------------------EDIT-------------------------------
I solved the problem using
InputStream is = this.getClass().getResourceAsStream("file.db");
BufferedReader br = new BufferedReader(new InputStreamReader(is));
Thank you so much for the help :)
By the time of deployment, those resources will likely become an embedded-resource. That being the case, the resource must be accessed by URL instead of File. See the info page for the tag, for a way to form an URL.
I don't understand how to use TextIO's readFile(String Filename)
Can someone please explain how can I read an external file?
public static void readFile(String fileName) {
if (fileName == null) // Go back to reading standard input
readStandardInput();
else {
BufferedReader newin;
try {
newin = new BufferedReader( new FileReader(fileName) );
}
catch (Exception e) {
throw new IllegalArgumentException("Can't open file \"" + fileName + "\" for input.\n"
+ "(Error :" + e + ")");
}
if (! readingStandardInput) { // close current input stream
try {
in.close();
}
catch (Exception e) {
}
}
emptyBuffer(); // Added November 2007
in = newin;
readingStandardInput = false;
inputErrorCount = 0;
inputFileName = fileName;
}
}
I had to use TextIO for a school assignment and I got stuck on it too. The problem I had was that using the Scanner class I could just pass the name of the file as long as the file was in the same folder as my class.
Scanner fileScanner = new Scanner("data.txt");
That works fine. But with TextIO, this won't work;
TextIO.readfile("data.txt"); // can't find file
You have to include the path to the file like this;
TextIo.readfile("src/package/data.txt");
Not sure if there is a way to get it to work like the Scanner class or not, but this is what I've been doing in my course at school.
The above answer (about using the correct file name) is correct, however, as a clarification, make sure that you actually use the proper file path. The file path suggested above, i.e. src/package/ will not work in all circumstances. While this will be obvious to some, for those of you who need clarification, keep reading.
For example (and I use NetBeans), if you have already moved the file into NetBeans, and the file is already in the folder you want it to be in, then right click on the folder itself, and click 'properties'. Then expand the 'file path' section by clicking on the three dots next to the hidden file path. You will see the actual file path in its entirety.
For example, if the entire file path is:
C:\Users..\NetBeansProjects\IceCream\src\icecream\icecream.dat
Then, in the java code file itself, you can write:
TextIo.readfile("src/icecream/icecream.dat");
In other words, make sure you include the words 'src' but also everything that follows the src as well. If it's in the same folder as the rest of the files, you won't need anything prior to the 'src'.
I am using the following java code in NetBeans to read and write to a file.
import java.io.*;
import java.util.*;
public class FileReadWrite {
StringTokenizer tokenizer;
BufferedReader inFile;
PrintWriter outFile;
File myFile;
private int[] highscores = new int[3];
public FileReadWrite() throws IOException, FileNotFoundException {
}
public int[] ReadFromSave() throws IOException, FileNotFoundException {
inFile = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/files/highscores.txt" )));
tokenizer = new StringTokenizer(inFile.readLine());
int i = 0;
while (tokenizer.hasMoreTokens()) {
highscores[i] = Integer.parseInt(tokenizer.nextToken());
i++;
}
inFile.close();
return highscores;
}
public void SaveFile(int score) throws IOException, FileNotFoundException {
if (score >= highscores[0]){
highscores[2] = highscores[1];
highscores[1] = highscores[0];
highscores[0] = score;
}
else if (score >= highscores[1]){
highscores[2] = highscores[1];
highscores[1] = score;
}
else if (score >= highscores[2]){
highscores[2] = score;
}
PrintWriter outFile = new PrintWriter(new FileWriter("/files/highscores.txt"));
String line = highscores[0] + " " + highscores[1] + " " + highscores[2];
outFile.println(line);
outFile.close();
}
}
I have coded a tetris program and want to save the highscores after each game. And when the user opens up the app next time they are shown the top 3 scores. The ReadFromSave() method started to work fine after I aded "getClass().getResourceAsStream". However I can't get the SaveFile() method working. I gives error "path/file not found". How should I use the PrintWriter in NetBeans so that it saves into the source packages and thus updating the jar. So when the app is fully closed and reopened it has the recent scores printed in. If this is not possible where can I save data so its not lost?
Thank you!!
If you want to be able to save the scores again, using getResourceAsStream isn't really a good idea - that's meant for resources which are bundled with the application, often within a jar file, and often read-only.
You might want to consider using the Java preferences API or work out some specific location for the file to use to store the high scores. Then just write to that file when saving, and read from it while loading. I wouldn't personally use PrintWriter (it swallows exceptions) or FileWriter (you can't specify the character encoding), but both should work. You just need to make sure you load the scores from the same file as you save it to. (It's not clear whether /files/highscores.txt is really an appropriate file to save to... do you have a /files directory? Were you expecting this to be relative to your application's working directory?)
(Also, it's a good idea to start following Java naming conventions, using camelCasing for method names... and use a try-with-resources statement to close writers, streams etc when you're finished with them, instead of manually calling close.)
You are mixing two things here. You are saving to an absolute path '/files/highscores.txt', but you are reading from the classpath, instead of the file system path. You'd have to choose one approach, but I'd stay away from absolute paths here.
However, a better approach might be to use the Preferences API, or Properties.load / store here. And if you're going to do IO operations, it might be better to look into Apache Commons IO, in which reading a file can be as trivial as doing FileUtils.readLines(file, "UTF-8");
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.
I have the following Java code which will search in an xml for a specific tag and then will add some text to it and save that file. I couldnt find a way to rename the emporary file to the original file. Please suggest.
import java.io.*;
class ModifyXML {
public void readMyFile(String inputLine) throws Exception
{
String record = "";
File outFile = new File("tempFile.tmp");
FileInputStream fis = new FileInputStream("InfectiousDisease.xml");
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
FileOutputStream fos = new FileOutputStream(outFile);
PrintWriter out = new PrintWriter(fos);
while ( (record=br.readLine()) != null )
{
if(record.endsWith("<add-info>"))
{
out.println(" "+"<add-info>");
out.println(" "+inputLine);
}
else
{
out.println(record);
}
}
out.flush();
out.close();
br.close();
//Also we need to delete the original file
//outFile.renameTo(InfectiousDisease.xml);//Not working
}
public static void main (String[] args) {
try
{
ModifyXML f = new ModifyXML();
f.readMyFile("This is infectious disease data");
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Thanks
First delete the original file and then rename the new file:
File inputFile = new File("InfectiousDisease.xml");
File outFile = new File("tempFile.tmp");
if(inputFile.delete()){
outFile.renameTo(inputFile);
}
A good method to rename files is.
File file = new File("path-here");
file.renameTo(new File("new path here"));
In your code there are several issues.
First your description mentions renameing the original file and adding some text to it. Your code doesn't do that, it opens two files, one for reading and one for writing (with the additional text). That is the right way to do things, as adding text in-place is not really feasible using the techniques you are using.
The second issue is that you are opening a temporary file. Temporary files remove themselves upon closing, so all the work you did adding your text disappears as soon as you close the file.
The third issue is that you are modifying XML files as plain text. This sometimes works as XML files are a subset of plain text files, but there is no indication that you attempted to ensure that the output file was an XML file. Perhaps you know more about your input files than is mentioned, but if you want this to work correctly for 100% of the input cases, you probably want to create a SAX writer that writes out all a SAX reader reads, with the additional information in the correct tag location.
You can use
outFile.renameTo(new File(newFileName));
You have to ensure these files are not open at the time.