I've been stuck on this problem for a few weeks now with no avail.
I am saving the contents of an array-list to a text file so that when the user opens the activity, the array list loads itself up for the user.
When i try to read the text file, and add the contents to the array-list, I get the following input inside the arraylist "Java.io.ObjectInputStream#b37391"
My array list will then look like this
[hello , leon, java.io.ObjectInputStream#b373791]
How can I read the text from the text file and display its contents on the array list
I have supplied the code used below, I have read many tutorials and stackoverflow questions but nothing seems to work. Some advice will be greatly appreciated.
try {
File f = new File(getFilesDir(), "anxfile.txt");
FileInputStream readtheting = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(readtheting);
ois.readObject();
arrayList.add(String.valueOf(ois));
adapter.notifyDataSetChanged();
ois.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Could you use this for reading:
List<String> strings = Files.readAllLines(new File(getFilesDir(), "anxfile.txt").toPath());
and this one for writing:
Files.write(new File(getFilesDir(), "anxfile.txt").toPath(), <someArray>);
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
After importing these then:
public class ReadFile{
public static void main(String[] args){
try {
BufferedReader reader = new BufferedReader(new FileReader("C:\\Users\\tmotswagole\\My Documents\\Example.txt"));
List<String> lines = new ArrayList<String>();
String line = null;
while ((line = reader.readLine()) != null)
{
lines.add(line);
}
reader.close();
for (int i =0; i<lines.size(); i++) {
String[] items = lines.get(i).split("", 1);
for (String s: items) {
System.out.println(s);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
This is how you would execute that code fully
Related
I have successfully added Csv reading functionality to my application. The setup that work is I have a base class called CSVReader. For each csv file, I create A new Class and it extends from CSVReader. The setup I am currently working on is to have only one class that can be used for any csv file. SO far my code seems to make sense, but clearly is not working therefore I need to fix something.
Here is the base CSVReader
package com.kbs.utilities.csvReader;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class CSVReader {
public ArrayList<String[]> readCsvFile(String filePath, boolean headerExists) { //Transfers info from CsvFile to an arraylist of string arrays
String line = "";
BufferedReader br = null;
ArrayList<String[]> arrayClone = new ArrayList<String[]>(); //Container to store contents of String array
try {
FileReader fileReader = new FileReader(filePath); //creates file reader object in the specified csv FIle
br = new BufferedReader(fileReader);
if(headerExists) { //if CSVFile has header then read the first line and put it into a variable
String headerLine = br.readLine();
headerLine.chars(); //pointless line of code, just here to remove the warning of unused variable
}
while((line = br.readLine())!= null) {
String[] currentRow = line.split(",");
arrayClone.add(currentRow);
}
} catch (FileNotFoundException e) {
// Error handling statement for throwing exception in case File isn't found
e.printStackTrace();
} catch(IOException e) {
//// Error handling statement for throwing exception in case File can't be accessed using BufferedReader object
e.printStackTrace();
}
finally {
if(br != null){
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return arrayClone;
}
}
This is the Class that extends CSVReader and is used to initiate the data from the specified csv
public class InitializeCSV extends CSVReader{
public ArrayList<Object> initCSV() {
String csvFile = "C:\\Users\\kamalu\\Desktop\\Developer\\misc\\sandbox\\kbs-petshop\\trunk\\WebContent\\WEB-INF\\data\\"+csvFileName+".csv";
boolean header = true;
ArrayList<String[]> csvStringArray = readCsvFile(csvFile, header); /
ArrayList<Object> list = new ArrayList<Object>();
for(String[] iteration : csvStringArray) {
Object[] iterationCopy = (Object[]) new Object();//Initializing using the array[] constructor
list.add(iterationCopy);
}
return list;
}
}
I have a file of multiple lines saved on my computer. In my java program, I am trying to ask the user to enter a string of letters or a word, and then have the program print out the lines only where that string of letters or word is. I know I have to import the scanner class, but how do I print out these user-specified lines?
Also, these lines of text are numbered (1-20). How do I print out just the text characters and ignore the integers when reprinting the original code? For example, one line of the code is "1. example of the first line of code"
Below is my code I have so far:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class BufferedReaderExample {
public static void main(String[] args) {
BufferedReader reader = null;
ArrayList <String> myFileLines = new ArrayList <String>();
try {
String sCurrentLine;
reader = new BufferedReader(new FileReader("/Users/wolftrek/Downloads/example.txt"));
while ((sCurrentLine = reader.readLine()) != null) {
myFileLines.add(sCurrentLine);
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
System.out.print(e.getMessage());
} finally {
try {
if (reader != null)reader.close();
} catch (IOException ex) {
System.out.println(ex.getMessage());
ex.printStackTrace();
}
}
for (int i = 0; i < myFileLines.size(); i++) {
if (myFileLines.get(i).contains("example word")) {
System.out.println(myFileLines.get(i));
}
}
}
}
I am making a Library System in Java, I am able to add new books, view and save them. However, I now want to search them using a Search window box. The saved data is located in a txt file. I would like to search for specific fields. I am thinking of implementing a linear search method, but am not too sure how to do it.
package bcu.storer;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import bcu.model.Book;
public class BookStorer {
public void StoreBooks(ArrayList<Book> booksList) throws IOException
{
FileWriter fw = new FileWriter(".\\data\\books.txt");
BufferedWriter bw = new BufferedWriter(fw);
try {
for (int i = 0; i < booksList.size(); i++)
{
String content = "";
Book book = booksList.get(i);
content += book.getIsbn()+"::";
content += book.getTitle()+"::";
content += book.getAuthor()+"::";
content += book.getPublisher()+"::";
content += book.getPudDate()+"::";
content += book.getStatus()+"\n";
bw.write(content);
}
System.out.println("Complete storing all books!");
} catch (IOException ae) {
ae.printStackTrace();
} finally {
try {
if (bw != null)
bw.close();
if (fw != null)
fw.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
This is the code which stores the book information to the TXT file, I would like to access this data in the search results.
I'm not sure if that's what you want. I help it helps you.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFromFile {
private static final String FILENAME = "pathToFile";
public static void main(String[] args) {
BufferedReader br = null;
FileReader fr = null;
try {
//br = new BufferedReader(new FileReader(FILENAME));
fr = new FileReader(FILENAME);
br = new BufferedReader(fr);
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
Array[String] tmpBook = sCurrentLine.split("::");
Book myBook = new Book(tmpBook(0),tmpBook(1),tmpBook(2), tmpBook(3), tmpBook(4), tmpBook(5))
/*Check here if is the book you are looking for*/
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
if (fr != null)
fr.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
This will read the file, line by line, and will get all the lines that match the search criteria.
This map provides the position (column) of each of the fields in the Book object.
private static Map<String, Integer> fieldToPositionMap = ImmutableMap.<String, Integer>builder()
.put("Isbn", 0)
.put("Title", 1)
.put("Author", 2)
.put("Publisher", 3)
.put("PudDate", 4)
.put("Status", 5)
.build();
Note: I have used GoogleGuava's ImmutableMap to construct the map, but you can build it in a traditional way.
The search method takes the name of the field and the value that you want to search for (eg, Isbn=ABC or Publisher=XYZ) and returns all the rows (as Book objects) that match the criteria.
public List<Book> search(String fieldName, String fieldValue) {
try {
return Files.lines(Paths.get("/path/to/txt/file")) //reads a file line by line
.filter(line -> {
String[] blocks = line.split("::");
//filter (choose) a row if value of the searched field equals the provided value
return blocks[fieldToPositionMap.get(fieldName)].equals(fieldValue);
})
.map(this::deserialize) //convert the line to a Book object
.collect(Collectors.toList()); //collect the result
} catch (IOException e) {
throw new RuntimeException(e);
}
}
//To convert a row from the file to a Book instance
private Book deserialize(String line) {
String [] blocks = line.split("::");
Book book = new Book();
book.setIsbn(blocks[0]);
book.setTitle(blocks[1]);
book.setAuthor(blocks[2]);
book.setPublisher(blocks[3]);
book.setPudDate(blocks[4]);
book.setStaus(blocks[5]);
}
Note: You might have to handle cases when a row does not have all fields
I am trying to load in a file from my computer with all the words of the dictionary in the file.
When I load the file i put the words into an array of strings.
I then want to eliminate all words that have more than 9 letters in them.
I then want to save the words that are 9 letters or smaller into another separate text file.
When i try to open the new file it only has 9 words in it, yet my print to the screen on eclipse will print the all words of nine or less letters.
Can anyone help!
This is a program that was gave to me as part of the question.
import java.io.*;
public class FileIO{
public String[] load(String file) {
File aFile = new File(file);
StringBuffer contents = new StringBuffer();
BufferedReader input = null;
try {
input = new BufferedReader( new FileReader(aFile) );
String line = null;
int i = 0;
while (( line = input.readLine()) != null){
contents.append(line);
i++;
contents.append(System.getProperty("line.separator"));
}
}
catch (FileNotFoundException ex) {
System.out.println("Can't find the file - are you sure the file is in this location: "+file);
ex.printStackTrace();
}
catch (IOException ex){
System.out.println("Input output exception while processing file");
ex.printStackTrace();
}
finally {
try {
if (input!= null) {
input.close();
}
}
catch (IOException ex) {
System.out.println("Input output exception while processing file");
ex.printStackTrace();
}
}
String[] array = contents.toString().split("\n");
for(String s: array){
s.trim();
}
return array;
}
public void save(String file, String[] array) throws FileNotFoundException, IOException {
File aFile = new File(file);
Writer output = null;
try {
output = new BufferedWriter( new FileWriter(aFile) );
for(int i=0;i<array.length;i++){
output.write( array[i] );
output.write(System.getProperty("line.separator"));
}
}
finally {
if (output != null) output.close();
}
}
}
this is the class i tried to use
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;
public class countdown{
public static void main(String args[]){
FileIO reader = new FileIO();
Scanner scan = new Scanner(System.in);
String[] inputs = reader.load("C:/Users/Sony/Documents/dict.csv"); //Reading the File as a String array from a file called dict
String[] input = new String[inputs.length]; //new String array for strings less than 9 letters
for(int i=0;i<inputs.length;i++){
if(inputs[i].length()<=9) { //if string of index i is less than 9
input[i]=inputs[i]; //add it to the new array called input
System.out.println(input[i]); //print line to check
}
}
try{
reader.save("C:/Users/Sony/Documents/dictnew.csv",input);
//this is where i save it to the new file called dictnew.
}catch (Exception e){
System.out.println(e.getClass());
}
}
}
After reading how you want you can split rest logic remains same.
package com.srijan.playground;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FilterLengthWords {
public static void main(String[] args) throws IOException {
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader("Sample.txt"));
bw = new BufferedWriter(new FileWriter("Output.txt"));
String tmp = null;
while((tmp=br.readLine())!=null) {
if(tmp.length()<=9) {
bw.write(tmp);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(br!=null) {
br.close();
br=null;
}
if(bw!=null){
bw.close();
bw=null;
}
}
}
}
Thanks
I need to make my program read a file, then take the numbers in the string and sort them into an array. I can get my program to read the file and put it to a string, but that's where I'm stuck. All the numbers are on different lines in the file, but appear as one long number in the string. This is what I have so far:
public static void main(String[] args) {
String ipt1;
Scanner fileInput;
File inFile = new File("input1.dat");
try {
fileInput = new Scanner(inFile);
//Reads file contents
while (fileInput.hasNext()) {
ipt1 = fileInput.next();
System.out.print(ipt1);
}
fileInput.close();
}
catch (FileNotFoundException e) {
System.out.println(e);
}
}
I recommend reading the values in as numeric types using fileInput.nextInt() or whatever type you want them, putting them in an array and using a built in sort like Arrays.sort. Unless I'm missing a more subtle point about the question.
If your task is just to get input from some file and you're sure the file has integers, use an ArrayList.
import java.util.*;
Scanner fileInput;
ArrayList<Double>ipt1 = new ArrayList<Double>();
File inFile = new File("input1.dat");
try {
fileInput = new Scanner(inFile);
//Reads file contents
while (fileInput.hasNext()){
ipt1.add(fileInput.nextDouble()); //Adds the next Double to the ArrayList
System.out.print(ipt1.get(ipt1.size()-1)); //Prints out what you just got.
}
fileInput.close();
}
catch (FileNotFoundException e){
System.out.println(e);
}
//Sorting time
//This uses the built-in Array sorting.
Collections.sort(ipt1);
However, if you DO need to come up with a simple array in the end, but CAN use ArrayLists, you can add the following:
Double actualResult[] = new Double[ipt1.size()]; //Declare array
for(int i = 0; i < ipt1.size(); ++i){
actualResult[i] = ipt1.get(i);
}
Arrays.sort(actualResult[]);
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class SortNumberFromFile {
public static void main(String[] args) throws IOException {
BufferedReader br = null;
try {
System.out.println("Started at " + LocalDateTime.now());
br = new BufferedReader(new FileReader("/folder/fileName.csv"));//Read data from file named /folder/fileName.csv
List<Long> collect = br.lines().mapToLong(a -> Long.parseLong(a)).boxed().collect(Collectors.toList());//Collect all read data in list object
Collections.sort(collect);//Sort the data
writeRecordsToFile(collect, "/folder/fileName.txt");//Write sorted data to file named /folder/fileName.txt
System.out.println("Ended at " + LocalDateTime.now());
}
finally {
br.close();
}
}
public static <T> void writeRecordsToFile(Collection<? extends T> items, String filePath) {
BufferedWriter writer = null;
File file = new File(filePath);
try {
if(!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
writer = new BufferedWriter(new FileWriter(filePath, true));
if(items != null && items.size() > 0) {
for(T eachItem : items) {
if(eachItem != null) {
writer.write(eachItem.toString());
writer.newLine();
}
}
}
} catch (IOException ex) {
}finally {
try {
writer.close();
} catch (IOException e) {
}
}
}
}