I have been trying to write an array to a file. I know how to write integers or String to a file but to bring an array confuses me. I am using this right now:
public static void write (String file, int[]x) throws IOException{
BufferedWriter outputWriter = null;
outputWriter = new BufferedWriter(new FileWriter(filename));
outputWriter.write("hi");// Here I know i cant just write x[0] or anything. Do i need
//to loop in order to write the array?
outputWriter.newLine();
outputWriter.flush();
outputWriter.close();
}
Like others said, you can just loop over the array and print out the elements one by one. To make the output show up as numbers instead of "letters and symbols" you were seeing, you need to convert each element to a string. So your code becomes something like this:
public static void write (String filename, int[]x) throws IOException{
BufferedWriter outputWriter = null;
outputWriter = new BufferedWriter(new FileWriter(filename));
for (int i = 0; i < x.length; i++) {
// Maybe:
outputWriter.write(x[i]+"");
// Or:
outputWriter.write(Integer.toString(x[i]);
outputWriter.newLine();
}
outputWriter.flush();
outputWriter.close();
}
If you just want to print out the array like [1, 2, 3, ....], you can replace the loop with this one liner:
outputWriter.write(Arrays.toString(x));
You can use the ObjectOutputStream class to write objects to an underlying stream.
outputStream = new ObjectOutputStream(new FileOutputStream(filename));
outputStream.writeObject(x);
And read the Object back like -
inputStream = new ObjectInputStream(new FileInputStream(filename));
x = (int[])inputStream.readObject()
If you're okay with Apache commons lib
outputWriter.write(ArrayUtils.join(array, ","));
Just loop over the elements in your array.
Ex:
for(int i=0; numOfElements > i; i++)
{
outputWriter.write(array[i]);
}
//finish up down here
private static void saveArrayToFile(String fileName, int[] array) throws IOException {
Files.write( // write to file
Paths.get(fileName), // get path from file
Collections.singleton(Arrays.toString(array)), // transform array to collection using singleton
Charset.forName("UTF-8") // formatting
);
}
If the result is for humans to read and the elements of the array have a proper toString() defined...
outputString.write(Arrays.toString(array));
Related
Currently working on a little project; as part of it I am creating a function called randomNumberGenerator which takes one parameter; string fileName which the name of the file/path that the user wants the integers to be written to. 10,000 random integers with a value between 0 and 100,000. From here, I want to convert the integers into an array of 4 bytes; and print the result in the filename which the user has passed into the function.
I've worked out how to generate the random numbers successfully, however I'm not able to convert it to a byte array successfully. Below is the function so far:
public void randomNumberGenerator(String fileName) throws FileNotFoundException {
try {
PrintWriter printWriter = new PrintWriter(fileName, StandardCharsets.UTF_8);
Random random = new Random();
for(int i=0; i<10000; i++) {
byte [] bytes = ByteBuffer.allocate(4).putInt(random.nextInt(100000)).array();
printWriter.println(Arrays.toString(bytes));
}
printWriter.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
When I try running my code thus far, I'm getting the error java.lang.NumberFormatException: For input string: "[0, 0, -115, -120]" - I've tried to fix this by doing printWriter.println(Arrays.toString(bytes)); instead, as I thought Arrays.toString was causing the error but I still can't get the function to turn the integers to a byte array succesffuly from there.
If anybody could advise me on what to do or where I'm going wrong, I'd appreciate it.
I believe this is what you were looking for, I'd just like to point out that the byte data type can hold values from -128 to 127 so for this program, you'd likely want to use a short as they can hold up to 32k.
I'll also point out that in most cases you don't need to mark the method as throwing the FNTE as you're already handling the exception within (although you could still mark it as throwing FNTE if you want to further handle it from wherever you're calling it from)
public static void main(String args[]) {
//Call the method, pass in the required args
genRandomNums(5, 4, 10000, "nums.txt");
}
public static void genRandomNums(int amount, int size, int maxVal, String fileName){
try {
//Create a file object and set the path to the passed file name
File file = new File(fileName);
//Create object of filewriter which will be used to write to the file
FileWriter fw = new FileWriter(file);
//Create an object of random, used to generate the random numbers
Random random = new Random();
//This loop controls how many arrays are created
for(int i = 0; i < amount; i++){
//Array to store the temp numbers, change this to int/long if you want to store above 32k value mark
short tempArr[] = new short[size];
//This loop controls setting the actual elements of the array
for (int j = 0; j < size; j++){
tempArr[j] = (short) random.nextInt(maxVal);
}
//Write the array to the file, add a new line so each array is separated
fw.write(Arrays.toString(tempArr) + "\n");
}
//Close and save the file
fw.close();
}catch (IOException ex){
ex.printStackTrace();
}
}
Try it like this. The values will be between -128 and 127 inclusive. Separated by a comma and a space.
public static void randomNumberGenerator(String fileName) throws FileNotFoundException {
Random random = new Random();
try (PrintWriter printWriter = new PrintWriter(fileName, StandardCharsets.UTF_8)) {
printWriter.print(random.nextInt(255)-128);
for(int i=0; i<39_999; i++) {
printWriter.printf(", %d", random.nextInt(255)-128);
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
I have been trying to write an array to a file. I know how to write integers or String to a file but to bring an array confuses me. I am using this right now:
public static void write (String file, int[]x) throws IOException{
BufferedWriter outputWriter = null;
outputWriter = new BufferedWriter(new FileWriter(filename));
outputWriter.write("hi");// Here I know i cant just write x[0] or anything. Do i need
//to loop in order to write the array?
outputWriter.newLine();
outputWriter.flush();
outputWriter.close();
}
Like others said, you can just loop over the array and print out the elements one by one. To make the output show up as numbers instead of "letters and symbols" you were seeing, you need to convert each element to a string. So your code becomes something like this:
public static void write (String filename, int[]x) throws IOException{
BufferedWriter outputWriter = null;
outputWriter = new BufferedWriter(new FileWriter(filename));
for (int i = 0; i < x.length; i++) {
// Maybe:
outputWriter.write(x[i]+"");
// Or:
outputWriter.write(Integer.toString(x[i]);
outputWriter.newLine();
}
outputWriter.flush();
outputWriter.close();
}
If you just want to print out the array like [1, 2, 3, ....], you can replace the loop with this one liner:
outputWriter.write(Arrays.toString(x));
You can use the ObjectOutputStream class to write objects to an underlying stream.
outputStream = new ObjectOutputStream(new FileOutputStream(filename));
outputStream.writeObject(x);
And read the Object back like -
inputStream = new ObjectInputStream(new FileInputStream(filename));
x = (int[])inputStream.readObject()
If you're okay with Apache commons lib
outputWriter.write(ArrayUtils.join(array, ","));
Just loop over the elements in your array.
Ex:
for(int i=0; numOfElements > i; i++)
{
outputWriter.write(array[i]);
}
//finish up down here
private static void saveArrayToFile(String fileName, int[] array) throws IOException {
Files.write( // write to file
Paths.get(fileName), // get path from file
Collections.singleton(Arrays.toString(array)), // transform array to collection using singleton
Charset.forName("UTF-8") // formatting
);
}
If the result is for humans to read and the elements of the array have a proper toString() defined...
outputString.write(Arrays.toString(array));
I want to write an ArrayList<String> into a text file.
The ArrayList is created with the code:
ArrayList arr = new ArrayList();
StringTokenizer st = new StringTokenizer(
line, ":Mode set - Out of Service In Service");
while(st.hasMoreTokens()){
arr.add(st.nextToken());
}
import java.io.FileWriter;
...
FileWriter writer = new FileWriter("output.txt");
for(String str: arr) {
writer.write(str + System.lineSeparator());
}
writer.close();
You can do that with a single line of code nowadays.
Create the arrayList and the Path object representing the file where you want to write into:
Path out = Paths.get("output.txt");
List<String> arrayList = new ArrayList<> ( Arrays.asList ( "a" , "b" , "c" ) );
Create the actual file, and fill it with the text in the ArrayList:
Files.write(out,arrayList,Charset.defaultCharset());
I would suggest using FileUtils from Apache Commons IO library.It will create the parent folders of the output file,if they don't exist.while Files.write(out,arrayList,Charset.defaultCharset()); will not do this,throwing exception if the parent directories don't exist.
FileUtils.writeLines(new File("output.txt"), encoding, list);
If you need to create each ArrayList item in a single line then you can use this code
private void createFile(String file, ArrayList<String> arrData)
throws IOException {
FileWriter writer = new FileWriter(file + ".txt");
int size = arrData.size();
for (int i=0;i<size;i++) {
String str = arrData.get(i).toString();
writer.write(str);
if(i < size-1)**//This prevent creating a blank like at the end of the file**
writer.write("\n");
}
writer.close();
}
If you want to serialize the ArrayList object to a file so you can read it back in again later use ObjectOuputStream/ObjectInputStream writeObject()/readObject() since ArrayList implements Serializable. It's not clear to me from your question if you want to do this or just write each individual item. If so then Andrey's answer will do that.
You might use ArrayList overloaded method toString()
String tmp=arr.toString();
PrintWriter pw=new PrintWriter(new FileOutputStream(file));
pw.println(tmp.substring(1,tmp.length()-1));
I think you can also use BufferedWriter :
BufferedWriter writer = new BufferedWriter(new FileWriter(new File("note.txt")));
String stuffToWrite = info;
writer.write(stuffToWrite);
writer.close();
and before that remember too add
import java.io.BufferedWriter;
Write a array list to text file using JAVA
public void writeFile(List<String> listToWrite,String filePath) {
try {
FileWriter myWriter = new FileWriter(filePath);
for (String string : listToWrite) {
myWriter.write(string);
myWriter.write("\r\n");
}
myWriter.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
I'm starting with java, and now I'm doing some exercises on read/writing files.
I write strings with this format:
String wordList: word1 word2 word3; word4 word5 word6; code
Then I write this to the file using this code:
public void writeSelling(String wordList) throws IOException {
fileOutPutStream = new FileOutputStream (file);
write= new ObjectOutputStream (fileOutPutStream);
write.writeObject(wordList);
write.close();
contador++;
}
But where I'm not getting able to do it right is when reading it. For now, what I get is a null when reading the content of the file, so I think that I'm doing something wrong on the method.
This is the method I use to read the file:
public ArrayList<Object> readSelling() throws Exception, FileNotFoundException, IOException {
ArrayList<Object> objectList = new ArrayList<Object>();
fileInPutStream = new FileInputStream (file);
read= new ObjectInputStream (fileInPutStream);
for (int i=0; i<contador; i++){
objectList.add(read.readObject());
}
read.close();
return objectList;
}
I call this method this way on the main file:
public static void listSelling(){
ArrayList objects;
try{
objects = sellingObject.readSelling();
for (Iterator it = sellingObject.iterator(); it.hasNext();) {
String s = (String)it.next();
System.out.println(s.toString());
}
}catch(FileNotFoundException fnfe){
System.out.println(fnfe.getMessage());
}catch(IOException ioe){
System.out.println(ioe.getMessage());
}catch(Exception e){
System.out.println(e.getMessage());
}
}
I don't have knowledge enough to work with the Iterator, so maybe I'm not using it right.
UPDATE -- Definition of "file.dat
This file is defined this way in other class:
private final String file;
public WriteReadObject(String file){
this.file= file;
}
Then in the main file is called this way:
static WriteReadObject selling= new WriteReadObject("file.dat");
UPDATE 2 --
I see that when I'm writing to the file, I'm writing a null value, and here is where it fails.
I have this:
String one = word1 word2 word3
String two = word4 word5 word6
Before call the write method to write on the file, I add these 2 strings in another string to get only one string. To do this I've created this method:
public String add(String c, String m){
sellinglist[contador] = c + m;
contador++;
String list= sellinglist[contador];
return list;
}
Where c is string one and m y string two
alexey28 said the right thing - you're rewriting the file and finally there's only the last insertion. Anyway it's not that simple to just change FileOutputStream argument to make it work - you can't just append to an ObjectOuputStream - if you would like to, see here. It will corrupt the stream what will result in StreamCorruptedException.
The best solution would be to open ObjectOutputStream once at the begining, write all objects you want and then close stream.
Update
It all depends on how you receive data which are to be written (If you are writing strings then it would be probably more comfortable to do it not in binary mode but text - here is tutorial which explains how to do that).
If you want code how to simply write list of Strings then you can try this:
/* writing */
public void writeSelling(List<String> wordLists) throws IOException {
fileOutPutStream = new FileOutputStream (file);
write= new ObjectOutputStream (fileOutPutStream);
for (String s : wordLists) {
write.writeObject(s);
}
write.close();
contador++;
}
Now you can change code in the place where you call writeSelling().
/* calling method */
List<String> wordLists = new ArrayList<String>();
{ // it's probably loop
String wordList = // somehow receive list like word1 word2 word3; word4 word5 word6; code
wordLists.add(wordList);
}
writeSelling(wordLists);
The rest remains the same. Don't call writeSelling() method multiple times, just once.
The problem is you are writing single object and try to read an array of objects. Every time you are writing object you rewrite current file. Change openning of output stream to append data to file (but don't forget to clear it when writing first object):
fileOutPutStream = new FileOutputStream (file, contador != 0);
I would like to receive some suggestions regarding a little problem I am going to solve in Java.
I have a file consisting in this format:
#
some text
some text
some text
#
some text
some text
some text
#
some text
some text
some text
...and so on.
I would need to read the next chunk of this text file, then to create an InputStream object consting of the read chunk and to pass the InputStream object to a parser. I have to repeat these operations for every chunk in the text file. Each chunk is written between the lines starting with #. The problem is to parse each section between the # tags using a parser which should read each chunk from an InputStream.
The text file could be big, so I would like to obtain good performance.
How could I solve this problem?
I have thought about doing something like this:
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
Scanner scanner = new Scanner(bufferedReader);
scanner.useDelimiter("#");
List<ParsedChunk> parsedChunks = new ArrayList<ParsedChunk>();
ChunkParser parser = new ChunkParser();
while(scanner.hasNext())
{
String text = scanner.next();
InputStream inputStream = new ByteArrayInputStream(text.getBytes("UTF-8"));
ParsedChunk parsedChunk = parser.parse(inputStream);
parsedChunks.add(parsedChunk);
inputStream.close();
}
scanner.close();
but I am not sure if it would be a good way to do it.
Thank you.
If I have understood correctly. This is what you are trying to achieve. FYI you will need JAVA 7 to get the below code running
public static void main(String[] args) throws IOException {
List<String> allLines = Files.readAllLines(new File("d:/input.txt").toPath(), Charset.defaultCharset());
List<List<String>> chunks = getChunks(allLines);
//Now you have all te chunks and you can process them
}
private static List<List<String>> getChunks(List<String> allLines) {
List<List<String>> result = new ArrayList<List<String>>();
int i = 0;
int fromIndex = 1;
int toIndex = 0;
for(String line : allLines){
i++;
if(line.startsWith("****") && i != 1){ // To skip the first line and the check next delimiter
toIndex = i-1;
result.add(allLines.subList(fromIndex, toIndex));
fromIndex = i;
}
}
return result;
}
didnt quite get the question but u could try using char at this moment as, storing all the character in char array & going thhrough a loop & condiional statement which breaks the string every time it encounters a'#'