i am trying to implement file handling into a small project i am currently working on. At the moment i can read in and write out an array of objects to an external .txt document but i am also trying to write out an int value which keeps track of the unique id of the last added element to an array List.
I am new to java, especially file handling. I am not sure if i can send in the int value along with the array list or if i need to create a new method and .txt document and write it to that. Below is what i have done so far, as you can see i have tried to send in the int with the array but this is as far as i can get.
public void writeToFile(List<? extends Serializable> team, int maleLastId) {
try {
outByteStream = new FileOutputStream(aFile);
OOStream = new ObjectOutputStream(outByteStream);
OOStream.writeObject(team);
outByteStream.close();
OOStream.close();
} catch(IOException e) {
JOptionPane.showMessageDialog(null,"I/O Error" + e + "\nPlease Contact your Administrator :-)");
}
}
A simple way to write to file is using the BufferedWriter class:
int x = 10;
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter("utfil.txt", true));
} catch (IOException e) {
e.printStackTrace();
}
writer.write(x);
Related
I have a class in Java which write a file using FileOutputStream and BufferedOutputStream. This is working fine but my intention is that I want to write any number of files in java not just one. Here is my code written in Java
public class FileToBeTaken{
public void fileBack(byte [] output) {
FileOutputStream fop = null;
BufferedOutputStream bos = null;
File file;
try {
file= new File("/Users/user/Desktop/newfile.txt");
fop = new FileOutputStream(file);
bos = new BufferedOutputStream(fop);
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
bos.write(output);
bos.flush();
bos.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bos != null) {
bos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Here fileBack method is called from another class inside a for loop n times. so for each time I need to write a new file onto my desktop as my code is I just take only the file for the last iteration. Also I should mention that for each iteration as parameter to this class is send one array of bytes which is taken by "byte [] output
Change
public void fileBack(byte [] output) {
to
public void fileBack(String fileName, byte [] output) {
Then change where you call method fileBack in your other class by providing the file name there. ie
byte output[] = //You already provide this byte array
String fileName = "/Users/user/Desktop/newfile.txt"
fileBack(fileName, output);
Try taking in the file path ..newfile.txt and making it into a parameter for the function. Then you can put a for loop in main or whoever is instantiating this object and call it n times. Does that help at all?
just add one static and private integer field inside FileToBeTaken class.
private static int index=0;
so there is no need to pass name of file to this class as you mentioned in question comments.
because i want to create these file names inside this class i wrote above
then use it in fileBack method and each time incremet it once in that method.
here is the changes on your code:
public class FileToBeTaken {
// index or number of new file, also number of all written files
// because it increments each time you call fileBack method.
private static int index = 0;
public void fileBack(byte[] output) {
FileOutputStream fop = null;
BufferedOutputStream bos = null;
File file;
try {
// use user_dir to place files on desktop,
// even on other machines which have other names except user.
String user_dir = System.getProperty("user.home").replace("\\", "/");
// use index to create name of file.
file = new File(user_dir+"/Desktop/newfile_" + (index++) + ".txt");
fop = new FileOutputStream(file);
bos = new BufferedOutputStream(fop);
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
bos.write(output);
bos.flush();
bos.close();
System.out.println("Done - "+file.getName());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bos != null) {
bos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
how to use it:
for (int i = 0; i < 10; i++) {
new FileToBeTaken().fileBack("some text".getBytes());
}
the output:
Done - newfile_0.txt
Done - newfile_1.txt
Done - newfile_2.txt
Done - newfile_3.txt
Done - newfile_4.txt
Done - newfile_5.txt
Done - newfile_6.txt
Done - newfile_7.txt
Done - newfile_8.txt
Done - newfile_9.txt
I'm running into a filenotfound when trying to read a file in internal storage; I'm pretty darn sure the file exists where I expect it and with appropriate permissions
I'm creating an android app where I'm saving off a string array list into files on the app's internal storage and then trying to randomly access the various lines from the file. I'm writing the file and reading the file within the same class, so I feel like I shouldn't have issues with like filepath and naming conventions.
Things I've verified or tried:
I've opened the files from the Android Device Monitor and the
contents and location are as expected.
The file permissions are -rw-rw----
I've grabbed the user.dir in both the read and write method and they both return "/" which seems incorrect, but the write method works (since the file is there)
Checked a ton of examples to double check formatting (for filename and for method use)
Read the File java reference texts as well as the android storage reference text
file name with and without ".txt"
I feel like I could probably hard code in the path but that sounds like a bad plan and shouldn't be necessary
Anyway here's wonderwall (or rather my code, but only the code parts that seemed relevant)
final List<String> affirmList = copyFilesToList("affirmation_file.txt");
final List<String> suggestList = copyFilesToList("suggestion_file.txt");
//copyFilesToList tries to open the file via selectSuggestion, if it is empty or fails, it goes into the create method
//opens both files and unpacks them into array list, feeds to unpack mehtods
private List<String> copyFilesToList(String fileName) {
String line="";
List<String> arr = new ArrayList<>();
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)))) {
while ((line = bufferedReader.readLine()) != null) {
arr.add(line);
}
}catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
arr.add("IO exception");
} finally {
//close stream
}
//test if arr contains something
//if not send to addDefaultLines
if (arr.isEmpty()){
arr = addDefaultLines(fileName);
}
return arr;
}
//
private List<String> addDefaultLines(String fileName){
List<String> arr = new ArrayList<String>(); //create arraylist
if (fileName=="affirmation_file.txt") {
//load affirmation values into arraylist
arr.add("affirmation 1");
arr.add("affirmation 2");
}
if (fileName=="suggestion_file.txt"){
//load suggestion values into arraylist
arr.add("suggestion 1");
arr.add("suggestion 2");
}
//sync arraylist with file
try{
FileOutputStream fos = openFileOutput(fileName, Context.MODE_PRIVATE);
String list = "";
int sz=arr.size();
//put the arraylist into a single string, for clarity
for (int i = 0; i < sz; i++) {
list += arr.get(i) + "\n"; //append with line breaks between
}
fos.write(list.getBytes());
}
catch (java.io.IOException e) {
e.printStackTrace();
}
return arr;
}
I need to loop through a .txt document called archive.txt until all data is in the document is exhausted.
I'm trying to return the data in a multidimensional array that creates a new row for every eighth data point.
So far, I have managed to loop through the data but can not seem to organise it.
Below is the function that can only spit out the data line per line.
private void findContract() {
Scanner input = null; // this is to keep the compiler happy
// as the object initialisation is in a separate block
try {
input = new Scanner(new File("archive.txt"));
} catch (FileNotFoundException e) {
System.out.println("File doesn't exist");
System.exit(1);
}
while (input.hasNext()) {
String dDate = input.next();
System.out.println(dDate);
}
input.close();
}
Example of first 8 data points from text file (archive.txt)
15-Sep-2015 2 1 12 N MT230N 617 CMcgee
The outcome of all of this is I need to be able to select a data point by row & column.
If anyone could show me the correct way it would be hugely appreciated. I have tried several methods & the above function is the last instance where it displays the data from the file.
With java 8 you can use this for any delimiter you may be using.
public static String[][] fileToMatriz(String file, String delimiter) throws IOException {
try (Stream<String> stream = Files.lines(Paths.get(file))) {
return stream.map(s -> s.split(delimiter))
.toArray(String[][]::new);
}
}
I am working on a simple save system for my game, which involves three methods, init load and save.
This is my first time trying out reading and writing to/from a file, so I am not sure if I am doing this correctly, therefore I request assistance.
I want to do this:
When the game starts, init is called. If the file saves does not exist, it is created, if it does, load is called.
Later on in the game, save will be called, and variables will be written to the file, line by line (I am using two in this example.)
However, I am stuck on the load function. I have no idea what do past the point I am on. Which is why I am asking, if it is possible to select a certain line from a file, and change the variable to that specific line.
Here is my code, like I said, I have no idea if I am doing this correctly, so help is appreciated.
private File saves = new File("saves.txt");
private void init(){
PrintWriter pw = null;
if(!saves.exists()){
try {
pw = new PrintWriter(new File("saves.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}else{
try {
load();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void save(){
PrintWriter pw = null;
try {
pw = new PrintWriter(new FileOutputStream(new File("saves.txt"), true));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
pw.println(player.coinBank);
pw.println(player.ammo);
pw.close();
}
public void load() throws IOException{
BufferedReader br = new BufferedReader(new FileReader(saves));
String line;
while ((line = br.readLine()) != null) {
}
}
I was thinking of maybe having an array, parsing the string from the text file into a integer, putting it into the array, and then have the variables equal the values from the array.
Seems like your file is a key=value structure, I suggest you'll use Properties object in java.
Here's a good example.
Your file will look like this:
player.coinBank=123
player.ammo=456
To save:
Properties prop = new Properties();
prop.setProperty("player.coinBank", player.getCoinBank());
prop.setProperty("player.ammo", player.getAmmo());
//save properties to project root folder
prop.store(new FileOutputStream("player.properties"), null);
Then you'll load it like this:
Properties prop = new Properties();
prop.load(new FileInputStream("player.properties"));
//get the property value and print it out
System.out.println(prop.getProperty("player.coinBank"));
System.out.println(prop.getProperty("player.ammo"));
Reading and writing are pretty much symmetric.
You're writing player.coinBank as the first line of the file, and player.ammo as the second line. So, when reading, you should read the first line and assign it to player.coinBank, then read the second line and assign it to player.ammo:
public void load() throws IOException{
try (BufferedReader br = new BufferedReader(new FileReader(saves))) {
player.coinBank = br.readLine();
player.ammo = br.readLine();
}
}
Note the use of the try-with-resources statement here, which makes sure the reader is closed, whatever happens in the method. You should also use this construct when writing to the file.
I am writing a program in Java that requires me to compare the data in 2 files. I have to check each line from file 1 against each line of file 2 and if I find a match write them to a third file. After I read to the end of file 2, how do I reset the pointer to the beginning of the file?
public class FiFo {
public static void main(String[] args)
{
FileReader file1=new FileReader("d:\\testfiles\\FILE1.txt");
FileReader file2=new FileReader("d:\\testfiles\\FILE2.txt");
try{
String s1,s2;
while((s1=file1.data.readLine())!=null){
System.out.println("s1: "+s1);
while((s2=file2.data.readLine())!=null){
System.out.println("s2: "+s2);
}
}
file1.closeFile();
file2.closeFile();
}catch (IOException e) {
e.printStackTrace();
}
}
}
class FileReader {
BufferedReader data;
DataInputStream in;
public FileReader(String fileName)
{
try{
FileInputStream fstream = new FileInputStream(fileName);
data = new BufferedReader(new InputStreamReader(fstream));
}
catch (IOException e) {
e.printStackTrace();
}
}
public void closeFile()
{
try{
in.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
I believe RandomAccessFile is what you need. It contains: RandomAccessFile#seek and RandomAccessFile#getFilePointer.
rewind() is seek(0)
I think the best thing to do would be to put each line from file 1 into a HashMap; then you could check each line of file 2 for membership in your HashMap rather than reading through the entire file once for each line of file 1.
But to answer your question of how to go back to the beginning of the file, the easiest thing to do is to open another InputStream/Reader.
Obviously you could just close and reopen the file like this:
while((s1=file1.data.readLine())!=null){
System.out.println("s1: "+s1);
FileReader file2=new FileReader("d:\\testfiles\\FILE2.txt");
while((s2=file2.data.readLine())!=null){
System.out.println("s2: "+s2);
//compare s1 and s2;
}
file2.closeFile()
}
But you really don't want to do it that way, since this algorithm's running time is O(n2). if there were 1000 lines in file A, and 10000 lines in file B, your inner loop would run 1,000,000 times.
What you should do is read each line and store it in a collection that allows quick checks to see if an item is already contained(probably a HashSet).
If you only need to check to see that every line in file 2 is in file 1, then you just add each line in file one to a HashSet, and then check to see that every line in file 2 is in that set.
If you need to do a cross comparison where you find every string that's in one but not the other, then you'll need two hash sets, one for each file. (Although there's a trick you could do to use just one)
If the files are so large that you don't have enough memory, then your original n2 method would never have worked anyway.
well, Gennady S. answer is what I would use to solve your problem.
I am writing a program in Java that requires me to compare the data in 2 files
however, I would rather not code this up again.. I would rather use something like http://code.google.com/p/java-diff-utils/
As others have suggested, you should consider other approaches to the problem. For the specific question of returning to a previous point in a file, java.io.FileReader would appear to inherit mark() and reset() methods that address this goal. Unfortunately, markSupported() returns false.
Alternatively, BufferedReader does support mark(). The program below prints true, illustrating the effect.
package cli;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class FileReaderTest {
public static void main(String[] args) {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(
new FileInputStream("src/cli/FileReaderTest.java")));
in.mark(1);
int i1 = in.read(); in.read(); in.read();
in.reset();
int i2 = in.read();
System.out.println(i1 == i2);
} catch (IOException e) {
e.printStackTrace(System.err);
}
}
}
As noted, there are better algorithms - investigate these
aside:
FileReader doesn't implement mark and reset, so trashgod's comments are inaccurate.
You'd either have to implement a version of this (using RandomAccessFile or what not) or wrap in a BufferedReader. However, the latter will load the whole thing in memory if you mark it
Just a quick Question. can't you keep one object pointed at the start of the file and traverse through the file with another object? Then when you get to the end just point it to the object at the beginning of the file(stream). I believe C++ has such mechanisms with file I/O ( or is it stream I/O)
I believe that you could just re-initialize the file 2 file reader and that should reset it.
If you can clearly indentify the dimension of your file you can use mark(int readAheadLimit) and reset() from the class BufferedReader.
The method mark(int readAhedLimit) add a marker to the current position of your BufferedReader and you can go back to the marker using reset().
Using them you have to be careful to the number of characters to read until the reset(), you have to specify them as the argument of the function mark(int readAhedLimit).
Assuming a limit of 100 characters your code should look like:
class MyFileReader {
BufferedReader data;
int maxNumberOfCharacters = 100;
public MyFileReader(String fileName)
{
try{
FileInputStream fstream = new FileInputStream(fileName);
data = new BufferedReader(new InputStreamReader(fstream));
//mark the current position, in this case the beginning of the file
data.mark(maxNumberOfCharacters);
}
catch (IOException e) {
e.printStackTrace();
}
}
public void resetFile(){
data.reset();
}
public void closeFile()
{
try{
in.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
If you just want to reset the file pointer to the top of the file, reinitialize your buffer reader. I assume that you are also using the try and catch block to check for end of the file.
`//To read from a file.
BufferedReader read_data_file = new BufferedReader(new FileReader("Datafile.dat"));'
Let's say this is how you have your buffer reader defined. Now, this is how you can check for end of file=null.
boolean has_data= true;
while(has_data)
{
try
{
record = read_data_file.readLine();
delimit = new StringTokenizer(record, ",");
//Reading the input in STRING format.
cus_ID = delimit.nextToken();
cus_name = delimit.nextToken();'
//And keep grabbing the data and save it in appropriate fields.
}
catch (NullPointerException e)
{
System.out.println("\nEnd of Data File... Total "+ num_of_records
+ " records were printed. \n \n");
has_data = false; //To exit the loop.
/*
------> This point is the trouble maker. Your file pointer is pointing at the end of the line.
-->If you want to again read all the data FROM THE TOP WITHOUT RECOMPILING:
Do this--> Reset the buffer reader to the top of the file.
*/
read_data_file = new BufferedReader(new FileReader(new File("datafile.dat")));
}
By reinitializing the buffer reader you will reset the file reader mark/pointer to the top of the file and you won't have to recompile the file to set the file reader marker/pointer to beginning/top of the file.
You need to reinitialize the buffer reader only if you don't want to recompile and pull off the same stunt in the same run. But if you wish to just run loop one time then you don't have to all this, by simply recompiling the file, the file reader marker will be set to the top/beginning of the file.