I'm just a beginner and got the following task:
Write first 100 positive and 100 negative integers to the file, listing them separated by a space.
Then read this file and put the read numbers into 2 files: positive_numbers and negative_numbers.
public static void main(String[] args) throws IOException {
File numbers = new File("C:\\numbers.txt");
File positivNumbers = new File("C:\\positivnumbers.txt");
File negativNumbers = new File("C:\\negativnumbers.txt");
try (
BufferedWriter wr = new BufferedWriter(new FileWriter(numbers));
BufferedReader rd = new BufferedReader(new FileReader(numbers));
BufferedWriter brnegativ = new BufferedWriter(new FileWriter(negativNumbers));
BufferedWriter brpositiv = new BufferedWriter(new FileWriter(positivNumbers));) {
if (numbers.exists()) {
for (int i = 0; i <= 100; i++) {
wr.write(String.valueOf((i) + " "));
}
for (int a = -1; a >= -100; a--) {
wr.write(((a) + " "));
}
String line = rd.readLine();
while (line != null) {
brpositiv.write(line);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
I could write numbers as a String to file "numbers". But I cannot read and write them in "positiv" output file.The file is empty. Where is my mistake?
After the writing you have to close wr so all data in memory gets flushed to the file. AFTER the close you can reopen it for read. So in your code you open rd too soon.
try (BufferedWriter wr = new BufferedWriter(new FileWriter(numbers));) {
for (int i = 0; i <= 100; i++) {
wr.write(String.valueOf((i) + " "));
}
for (int a = -1; a >= -100; a--) {
wr.write(((a) + " "));
}
} catch (IOException e) {
e.printStackTrace();
}
// file is closed by try-with-resources ...
// ... so now we can open it for read:
try (BufferedReader rd = new BufferedReader(new FileReader(numbers));
BufferedWriter brnegativ = new BufferedWriter(new FileWriter(negativNumbers));
BufferedWriter brpositiv = new BufferedWriter(new FileWriter(positivNumbers));) {
String line = rd.readLine();
while (line != null) {
brpositiv.write(line);
// TODO : split logic
}
} catch (IOException e) {
e.printStackTrace();
}
I want to save a 2-dimensional String Array in a .txt file and load it from it in my app. The Array should be editable and expandable in the app. I am not really experienced with BufferedWriter, BufferedReader, FileInputStream and FileOutputStream and things like this.
I have problems with this code: The BufferedWriter and BufferedReader throws a NullPointerException and I don't know why. Or does everyone know a possibillity to do this with FileInputStream and FileoutputStream?
public String path =
Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyFile";
File dir = new File(path);
if(!dir.exists()) {
dir.mkdirs();
}
File file = new File(path + "/savedFile.txt");
public static void Save(File file, String[][] list)
{
BufferedWriter writer = null;
StringBuilder builder = new StringBuilder();
try
{
writer = new BufferedWriter(new FileWriter(file));
}
catch (IOException e) {e.printStackTrace();}
try
{
try
{
for(int i = 0; i < list.length; i++)
{
for(int j = 0; j < list[i].length; j++)
{
builder.append(list[i][j]+"");
if(j < list.length - 1)
builder.append(",");
}
builder.append("\n");
}
}
catch (Exception e) {e.printStackTrace();}
}
finally
{
try
{
writer.write(builder.toString());
writer.close();
}
catch (IOException e) {e.printStackTrace();}
}
}
public static String[][] Load(File file)
{
BufferedReader reader = null;
try
{
reader = new BufferedReader(new FileReader(file));
}
catch (FileNotFoundException e) {e.printStackTrace();}
String test;
String[][] array = new String[4][2]; //the indexs are for a specific example; it should be expandable, but I solve that myself
String line;
int row = 0;
try
{
while ((line = reader.readLine()) != null) {
String[] cols = line.split(",");
int col = 0;
for (String c : cols) {
array[row][col] = c;
col++;
}
row++;
}
}
catch (IOException e) {e.printStackTrace();}
return array;
}
I think that the problem would be with the scope of variables in multiple braces you've used. try this code:
public static void Save(File file, String[][] list) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < list.length; i++) {
for (int j = 0; j < list[i].length; j++) {
builder.append(list[i][j] + "");
if (j < list.length - 1) {
builder.append(",");
}
}
builder.append("\n");
}
try {
Writer writer = new BufferedWriter(new FileWriter(file));
try {
writer.write(builder.toString());
} finally {
writer.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
I'm almost there, but I'm getting an error to delete a catch for exceptions. Second to the last line of code. Also is there any way to only choose specific spots on the array to print out to the text file? Thanks
import java.io.*;
import java.util.*;
public class Project_Space
{
public static void main(String[] args)
{
// 2D Array of Passengers and Pilots objects- the Passengers class is in the Person.java file
Person[][] Members ;
int num_flights= 6; //create the "x" bound/size of the array
int num_passengers= 9; //create the "y" bound/size of the array
Members = new Person[num_flights][num_passengers];
//The Members array at index 0 is the first company
Members[0][0] = new Person.Flight(1); //This spot in the array is for the Company number in the first spot. Everything else are place holders for data that doesn't pertain to the company
Members[0][1] = new Person.Pilots(1,"1877963200","Amadeus","Durrutti","Buckminster Cornwallis","1288211435", 11); //This spot in the array is for the first team member of company #1
Members[0][2] = new Person.Pilots(2,"6054350085","Sirius","Sassafrass","Ali Bababa","1776812631", 9);
Members[0][3] = new Person.Passengers(1,"7065253333","Amy","Hartman","Betty Sue","7708889999", 3, 50000,"0554055405540554");
Members[0][4] = new Person.Passengers(2,"7545251337","Amanda","Zion","Beatrice Twix","7448656577", 4, 2000,"0554055405541111");
Members[0][5] = new Person.Passengers(3,"8904448899","Janet","Graves","Neal Wade","4445556666", 5, 3000, "9031029266161432");
Members[0][6] = new Person.Passengers(4,"8902234567","Kristen","Pickering","Christopher Soto","5685461208", 6, 51500, "0985028135114275");
Members[0][7] = new Person.Passengers(5,"5000893778","Julianna","Estrada","Jill Hansen","2770779833", 7, 0, "0213595590286251");
Members[0][8] = new Person.Passengers(6,"2080670437","Regena","Mckenzie","Vicki Cook","6224215759", 8, 250, "8204699533830238");
....
Arrays.deepToString(Members);
PrintWriter writer;
try
{
writer = new PrintWriter("flightnames.txt");
for (int i = 0; i<Members.length; i++){
for(int j = 0; j<Members.length; j++){
writer.print(Members[i][j] + ",");
}writer.println();
}}
catch (FileNotFoundException e){
System.out.println("Error: " + e.getMessage());
}
finally{if (writer!=null)
writer.close();
catch (Exception e)
{System.out.println("Could not close writer");}
}
}
}
Move your finally block, and it should compile properly. For the future use an IDE and use formatting, it will show you your mistakes faster:)
Arrays.deepToString(Members);
PrintWriter writer;
try {
writer = new PrintWriter("flightnames.txt");
for (int i = 0; i < Members.length; i++) {
for (int j = 0; j < Members.length; j++) {
writer.print(Members[i][j] + ",");
}
writer.println();
}
} catch (FileNotFoundException ex) {
System.out.println("Error: " + ex.getMessage());
} catch(Exception ex){
System.out.println("Could not close writer"+ ex.getMessage());
} finally {
if (writer != null) {
try{
writer.close();
} catch(IOException ex) {
System.out.print("Error while closing file: "+ ex.getMessage())
}
}
}
It seems like what you actually want is this:
...
finally {
if (writer!=null) {
try {
writer.close();
} catch (Exception e) {
System.out.println("Could not close writer");
}
}
}
That is, have a dedicated try/catch around your writer.close() call to report that an error was thrown by closing the writer.
Also, you need to initialise the writer to null. You can't do if (writer!=null) (or indeed anything else with writer) if the writer might never have been assigned.
So change your writer declaration to:
PrintWriter writer = null;
I have a for loop that runs 20.000 times with a for loop inside it that runs 20.000 times as well which adds up to a total of 400 million.
in the for loop it adds 20.000 numbers to a string and then writes this string into a txt file. after the writing the string is being set empty like this :String Name = "";
so i will get a total of 20.000 text files with each 20.000 numbers in it.
now if the for loop has created about 200 files it starts to run out of memory and crashes eventually.
how can i avoid this?
-- here is the code --
public static void mapScanner()
{
String content = "";
for(int z = -10000; z < 10000; z++)
{
Util.CreateFile(z);
for(int x = -10000; x < 10000; x++)
{
Block block = Bukkit.getServer().getWorld("world").getBlockAt(x, Bukkit.getServer().getWorld("world").getHighestBlockYAt(x, z) -1, z);
if(block.getType() != Material.AIR)
{
content += Blocks.blockID(block.getType());
}
}
try
{
File file = new File("plugins/Map/" + z + ".txt");
System.out.println(content);
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
content = "";
System.out.println("The file : " + z + ".txt has been created and written.");
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
block.getType() just returns a number.
General code :
for(int x = 0; x < 20000; x++)
{
String content = "";
CreateFile(x);
for(int z = 0; z < 20000; z++)
{
content += "1";
}
try
{
File file = new File("Map/" + x + ".txt");
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
//System.out.println("The file : " + x + ".txt has been created and written.");
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static void CreateFile(int z) {
File file = new File("Map/" + z + ".txt");
boolean fileCreated = false;
try {
fileCreated = file.createNewFile();
} catch (IOException ioe) {
//System.out.println("Error while creating empty file: " + ioe);
}
if (fileCreated) {
//System.out.println("Created empty file: " + file.getPath());
} else {
//System.out.println("Failed to create empty file: " + file.getPath());
}
}
You will always have performance problems if you keep all contents in memory, show me some code to help you.
One way to me to do this, it's write directly to the file so no need to keep the string in memory.
Sorry for my grammar anyway, I'm not great at writing...
Try something like this instead:
public static void mapScanner()
{
String content = "";
for(int z = -10000; z < 10000; z++)
{
File file = new File("plugins/Map/" + z + ".txt");
// if file doesn't exists, then create it, this inside another try.
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fw = new FileOutputStream(file);
OutputStream bw = new BufferedOutputStream(fw);
for(int x = -10000; x < 10000; x++)
{
Block block = Bukkit.getServer().getWorld("world").getBlockAt(x, Bukkit.getServer().getWorld("world").getHighestBlockYAt(x, z) -1, z);
if(block.getType() != Material.AIR)
{
string temp = Blocks.blockID(block.getType());
System.out.println(temp);
bw.write(temp.getBytes());
}
}
try
{
// Close all
bw.flush();
bw.close();
fw.close();
file.close();
System.out.println("The file : " + z + ".txt has been created and written.");
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
replace String content = "" with StringBuilder content = new StringBuilder() and content += Blocks.blockID(block.getType()) with content.append(Blocks.blockID(block.getType()))
this should make your loop run quite a lot faster. i doubt it will help with your OutOfMemory problem, though.
I have a method to store the input of a 2D array in a .txt file. However, even with the true put on the end of FileWriter fw = new FileWriter("CBB.dat");, something that usually allows for appending in past projects, the file still only receives one entry before writing over it with the next entry. How would this be fixed?
public void Save(String[][] EntryList)
{
try
{
File file = new File("CBB.dat");
// if file doesnt exists, then create it
if (!file.exists())
{
file.createNewFile();
}
if (EntryList[0][0] != null)
{
DataOutputStream outstream;
outstream = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
for (int row = 0; row < EntryList.length; row++)
{
for (int col = 0; col < EntryList[row].length; col++)
{
if (EntryList[row][col] != null) outstream.writeUTF(EntryList[row][col]);
}
outstream.close();
}
}
else System.out.print("Something is wrong");
} catch (IOException e)
{
e.printStackTrace();
}
}
Use a CharSequence instead of a String[][] (or you could also use variable arity parameters):
public static void save(CharSequence entryList)
{
BufferedReader read;
BufferedWriter write;
File file = new File("CBB.dat");
if (!file.exists())
{
try
{
file.createNewFile();
} catch (Exception e)
{
e.printStackTrace();
}
}
try
{
read = new BufferedReader(new FileReader(file));
String complete = "";
String line = null;
while ((line = read.readLine()) != null)
{
complete += line + "\n";
}
read.close();
write = new BufferedWriter(new FileWriter(file));
write.append(complete);
write.append(entryList);
write.flush();
write.close();
} catch (Exception e)
{
e.printStackTrace();
}
}