How to write data to a text file in Java [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm creating a sport prediction game for my Grade 11 year and I'm having issues writing data to a text file. I'm using NetBeans 7.3.1. I'm using a button where every time it is pressed data entered by the user must be written to the text file. The text file is empty in the beginning and I need to add data to it. After the first click on the button the data keep rewriting itself and the new data is not added. It needs to be in a new line each time. Thank you very much. Some coding would be awesome!

I just did a quick search for appending to a file (usually a good thing to do): this question seems to be what your looking for.

I haven't tested this, but this should work:
private boolean appendToFile(String fileName, String data, String lineSeparator)
throws IOException {
FileWriter writer = null;
File file = new File(fileName)
if (!file.exists()) {
file.createNewFile();
}
try {
writer = new FileWriter(fileName, true);
writer.append(data);
writer.append(lineSeparator);
} catch (IOException ioe) {
return false;
} finally {
if (writer != null) {
writer.close();
}
}
return true;
}

Related

Why can't I read all lines of a file in java? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm trying to make a text editor in Java, but I can't seem to get the "open file" feature to work. When I run the code, it only displays the first line of a file. I've tried all of the code snippets from: How to read a large text file line by line using Java?, but it still reads the first line only.
This is what I have tried:
JMenuItem mntmOpen = new JMenuItem("Open");
mntmOpen.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0));
mntmOpen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == mntmOpen) {
int returnVal = fc.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
//This is where a real application would open the file.
Path HI = file.toPath();
try( Stream<String> lines = Files.lines(HI)
){
for( String line : (Iterable<String>) lines::iterator )
{
editorPane.setText(line);
}
}catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
});
Check out this answer here, you should be able to use the section in the while loop. Pretty straight forward run until null which basically states that the buffer will continue to read until the reader sends back a null pointer in which case there is nothing left in the file. If this doesn't work then we can take a look at it again. Also you got downvoted for asking a question without searching for an answer first. https://www.caveofprogramming.com/java/java-file-reading-and-writing-files-in-java.html

Get something like Resultset from data file [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
I want to read a delimiter-separated or fixed-width file (of defined layout), and want to get something like a Resultset through which I can iterate throgh the record.
Is there any reliable library for doing this? If not then can anyone please suggest me how I should proceed? An example code snippet will be very helpful to me.
You can use java ios to iterate each line in the text file and then implement your own logic to split the line and do as desired.
public static void main(String args[]) throws Exception {
//input file
File inputFile = new File("c:/hadoop/sample.txt");
BufferedReader br = new BufferedReader(new FileReader(inputFile));
String s = null;
while ((s = (br.readLine())) != null) {
//check each line and do the logic may be split or based on the requirement
String cols[] =s.split("|");
}
}
public static Stream<String> lines(Path path)
throws IOException
Read all lines from a file as a Stream. Bytes from the file are decoded into characters using the UTF-8 charset.
This method works as if invoking it were equivalent to evaluating the expression:
Files.lines(path, StandardCharsets.UTF_8)
Parameters:
path - the path to the file
Returns: the lines from the file as a Stream
Throws:
IOException - if an I/O error occurs opening the file
SecurityException - In the case of the default provider, and a security manager is installed, the checkRead method is invoked to check read access to the file.
Since: 1.8
Files.lines(Path) expects a Path argument and returns a Stream<String>.
This is Java 8, so you can use lambda expressions or method references to provide a Consumer argument.
public class FixedWidthFile {
public static void main(String JavaLatte[]) {
Path path = Paths.get("/home/sample.txt");
try {
Stream<String> lines = Files.lines(path);
lines.forEach(s -> System.out.println(s));
} catch (IOException ex) {
}
}
}
Reference: Class Files

Cant find file in the raw folder in android [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I have a file dictionary.txt and I need to get that file from the raw folder so I googled around and found this:
Here's an example:
"android.resource:///"+getPackageName()+ "/" + R.raw.dictionary;
but it did not work, Any idea?
Edit:
here is what i am doing
for(String line: FileUtils.readLines(file))
{
if(line.toLowerCase().equals(b.toLowerCase()))
{
valid = true;
}
}
You can get an input stream on a raw resource by using:
getResources().openRawResource(R.raw.dictionary);
EDIT:
From your edit, there really isn't a reason as to why you would specifically need the file rather than just using the input stream available from the openRawResource(int id) method...just use an existing java class http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#Scanner%28java.io.InputStream,%20java.lang.String%29.
Scanner scanner = new Scanner(getResources().openRawResource(R.raw.dictionary));
while(scanner.hasNextLine()){
{
if(scanner.nextLine().toLowerCase().equals(b.toLowerCase()))
{
valid = true;
}
}
}
Unfortunately you can not create a File object directly from the raw folder. You need to copy it in your sdcard or inside the application`s cache.
you can retrieve the InputStream for your file this way
InputStream in = getResources().openRawResource(R.raw.yourfile);
try {
int count = 0;
byte[] bytes = new byte[32768];
StringBuilder builder = new StringBuilder();
while ( (count = is.read(bytes,0 32768) > 0) {
builder.append(new String(bytes, 0, count);
}
is.close();
reqEntity.addPart(new FormBodyPart("file", new StringBody(builder.toString())));
} catch (IOException e) {
e.printStackTrace();
}
EDIT:
to copy it over to internal storage:
File file = new File(this.getFilesDir() + File.separator + "fileName.ext");
try {
InputStream inputStream = resources.openRawResource(R.id._your_id);
FileOutputStream fileOutputStream = new FileOutputStream(file);
byte buf[]=new byte[1024];
int len;
while((len=inputStream.read(buf))>0) {
fileOutputStream.write(buf,0,len);
}
fileOutputStream.close();
inputStream.close();
} catch (IOException e1) {}
Now you have a File that you can access anywhere you need it.
Place the file in the assets folder and open it like this
getResources().getAssets().open("dictionary.txt");

Saving game state [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm making a typing only game(no graphics) in which I need to save the state of the game and reload later. I've been thinking but could think of nothing(I'm not a very experienced programmer). Could someone enlighten me?
You need your class to implement Serializable interface. Then write the object to a file. Then on start up read the file back again.
To serialize an object means to convert its state to a byte stream so
that the byte stream can be reverted back into a copy of the object. A
Java object is serializable if its class or any of its superclasses
implements either the java.io.Serializable interface or its
subinterface, java.io.Externalizable. Deserialization is the process
of converting the serialized form of an object back into a copy of the
object.
The beauty of Serialzable interface is that you do not need to implement any methods. It is a marking interface. You just make a class Serializable and then write it out to a file.
Word of caution here: You need to truncate the file every time you write to it. Do not try to append data to it. It corrupts the header of the file.
Tutorials here: http://docs.oracle.com/javase/tutorial/jndi/objects/serial.html
You can use ObjectOutputStream and call its method writeObject to save your game state.
And use ObjectInputStream and call its method readObject to load game states.
e.g.
Save Game state
public void saveGameDataToFile(File file) {
try {
FileOutputStream fileStream = new FileOutputStream(file);
ObjectOutputStream objectStream = new ObjectOutputStream(fileStream);
objectStream.writeObject(flag);
objectStream.writeObject(color);
objectStream.writeObject(snake);
objectStream.writeObject(food);
objectStream.writeObject(new Integer(score));
objectStream.writeObject(barrier);
objectStream.writeObject(new Boolean(needToGenerateFood));
objectStream.writeObject(new Boolean(needToGenerateBarrie));
objectStream.close();
fileStream.close();
JOptionPane.showConfirmDialog(frame,
"Save game state successfully.",
"Snake Game",
JOptionPane.DEFAULT_OPTION);
} catch (Exception e) {
JOptionPane.showConfirmDialog(frame,
e.toString() + "\nFail to save game state.",
"Snake Game",
JOptionPane.DEFAULT_OPTION);
}
}
Load Game state
public void loadGameDataFromFile(File file) throws ClassNotFoundException{
... ...
FileInputStream fileStream = new FileInputStream(file);
ObjectInputStream objectStream = new ObjectInputStream(fileStream);
svaedFlag = (int[][]) objectStream.readObject();
savedColor = (Color[][]) objectStream.readObject();
savedSnake = (Snake) objectStream.readObject();
savedFood = (Grid) objectStream.readObject();
savedScore = (Integer) objectStream.readObject();
savedBarriers =(Barriers) objectStream.readObject();
savedNeedToGenerateFood = (Boolean)objectStream.readObject();
savedNeedToGenerateBarrie = (Boolean)objectStream.readObject();
... ...
}
for persisting the Object state you can
use serialization
safe the contents to file as text or xml
save the contents to database (sqlLite,hsql)

Adding new lines to a .txt file [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm studying Chinese.
I have an iPhone app with optical character recognizer that can capture vocab lists in this format: (character TAB pronunciation TAB definition)
淫秽 TAB yin2hui4 TAB obscene; salacious; bawdy
网站 TAB wang3zhan4 TAB website
专项 TAB zhuan1xiang4 TAB attr. earmarked
but the flashcard app I use requires this format: (Character NEWLINE Pronunciation NEWLINE Definition)
淫秽
yin2hui4
obscene; salacious; bawdy
网站
wang3zhan4
<computing> website
专项
zhuan1xiang4
attr. earmarked
I only know a little Java. How do I convert the first format to the second format?
Obviously, we don't want to do your homework. But we don't want to leave you stranded either.
I've left many things open and the below is just a Java-looking pseudocode. You can start here...
FileReader reader = ... // open the file reader using the input file
FileWriter writer = ...// open a file for writing output
while(the stream doesn't end) { // provide the condition, as must be
String line = ... // read a line from the reader
String character = line.substring(0, line.indexOf("\t")),
pronounciation = line.substring(character.length() -1).substring(line.indexOf("\t", character.length()),
definition = line.substring(line.lastIndexOf("\t")); // Obviously, this isn't accurate.... you need to work around this.
writeLineToFile(character)
writeLineToFile(pronounciation)
writeLineToFile(definition)
}
close the reader and writer
Even though it looks like an Exercise. But ideally you can do.
Get the file contents (use commons-io)
Replace TAB with new line and write to file
example code
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
public class Test {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
String path = "C:/test.txt";
// TODO Auto-generated method stub
File file = new File(path);
String string = FileUtils.readFileToString(file);
String finalString = string.replaceAll("\t", "\n");
FileUtils.write(file, finalString);
}
}
The file now would look like
淫秽
yin2hui4
obscene; salacious; bawdy
网站
wang3zhan4
website
专项
zhuan1xiang4
attr. earmarked

Categories