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();
}
}
Related
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 want to split csv file into multiple csv files depending on column value.
Structure of csv file: Name,Id,Dept,Course
abc,1,CSE,Btech
fgj,2,EE,Btech
(Rows are not separated by ; at end)
If value of Dept is CSE or ME , write it to file1.csv, if value is ECE or EE write it to file2.csv and so on.
Can I use drools for this purpose? I don't know drools much.
Any help how it can be done?
This is what I have done yet:
public void run() {
String csvFile = "C:/csvFiles/file1.csv";
BufferedReader br = null;
BufferedWriter writer=null,writer2=null;
String line = "";
String cvsSplitBy = ",";
String FileName = "C:/csvFiles/file3.csv";
String FileName2 = "C:/csvFiles/file4.csv";
try {
writer = new BufferedWriter(new FileWriter(FileName));
writer2 = new BufferedWriter(new FileWriter(FileName2));
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
String[] values=line.split(cvsSplitBy);
if(values[2].equals("CSE"))
{
writer.write(line);
}
else if(values[2].equals("ECE"))
{
writer2.write(line);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
writer.flush();
writer.close();
writer2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
1) First find column index using header row or if header is not present then by index
2) Follow below algorithm which will result map of key value where key is column by which split is performed
global resultMap;
Method add(key,row) {
data = (resultMap.containsKey(key))? resultMap.get(key):new ArrayList<String>();
data.add(row);
resultMap.put(key, data );
}
Method getSplittedMap(List rows) {
for (String currentRow : rows) {
add(key, currentRow);
}
return resultMap;
}
hope this helps.
FileOutputStream f_ECE = new FileOutputStream("provideloaction&filenamehere");
FileOutputStream f_CSE_ME = new FileOutputStream("provideloaction&filenamehere");
FileInputputStream fin = new FileinputStream("provideloaction&filenamehere");
int size = fin.available(); // find the length of file
byte b[] = new byte[size];
fin.read(b);
String s = new String(b); // file copied into string
String s1[] = s.split("\n");
for (int i = 0; i < s1.length; i++) {
String s3[] = s1[i].split(",")
if (s3[2].equals("ECE"))
f_ECE.write(s1.getBytes());
if (s3[2].equals("CSE") || s3.equals("EEE"))
f_CSE_ME.write(payload.getBytes());
}
I have a class which can read a file, modify it an write it to another file. The characters in the output are correct , the only problem is that the lines need to have a length of 12 chars.
How can I achieve this with my existing code?(I wrote a comment where in the code I want to do this)
My input file: http://gyazo.com/13fe791d24ef86e29ab6a6e89d0af609
The current output: http://gyazo.com/cc195c1d59a9d1fe3b4f2c54e71da8eb
The output I want : http://gyazo.com/04efcbb05c5d56b6e28972feb8c43fb8
String line;
StringBuilder buf = new StringBuilder();
public void readFile(){
BufferedReader reader = null;
try {
File file = new File("C:/Users/Sybren/Desktop/Invoertestbestand1.txt");
reader = new BufferedReader(new FileReader(file));
//String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
//buf.append(line);
processInput();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
};
}
}
public void processInput(){
buf.append(line);
if (buf.length()>7){
buf.append("-");
}
/* if a * is followed by * change them to a ! */
for (int index = 0; index < buf.length(); index++) {
if (buf.charAt(index) == '*' && buf.charAt(index+1) == '*') {
buf.setCharAt(index, '!');
buf.deleteCharAt(index+1);
}
}
// get last character from stringbuilder and delete
buf.deleteCharAt(buf.length()-1);
/* start with a new line if the line length is bigger than 12 - how to do it? */
//???
}
public void writeFile() {
try {
String content = buf.toString();
File file = new File("C:/Users/Sybren/Desktop/uitvoer1.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}}
Would something along these lines help?
for (int i=13;i<buf.size();i+=13) {
buf.insert(i, '\n');
i++; // to account for the newline char just added
}
The numbers used may not be correct, either because of misunderstanding of the question or because it isn't tested.
for (int index = 0; index < buf.length(); index++) {
if (buf.charAt(index) == '*' && buf.charAt(index+1) == '*') {
buf.setCharAt(index, '!');
buf.deleteCharAt(index+1);
}
}
There will be an java.lang.ArrayIndexOutOfBoundsException at the end of the loop when you you call index+1
I have a program which reads a file I can change the content of this file and after that it's written to another file. The input file looks like this: http://gyazo.com/4ee1ade01378238e2c765e593712de7f and the output has to look like this http://gyazo.com/5a5bfd00123df9d7791a74b4e77f6c10 my current output is http://gyazo.com/87a83f4c6d48aebda3d11060ebad66c2 so how to change my code that it's starts a new line after 12 characters? Also I want to delete the last !.
public class readFile {
String line;
StringBuilder buf = new StringBuilder();
public void readFile(){
BufferedReader reader = null;
try {
File file = new File("C:/Users/Sybren/Desktop/Invoertestbestand1.txt");
reader = new BufferedReader(new FileReader(file));
//String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
//buf.append(line);
processInput();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
};
}
}
public void processInput(){
buf.append(line);
if (buf.length()>7){
buf.append("-");
//buf.append(System.getProperty("line.separator"));
}
/* start with a new line if the line length is bigger than 12 - in progress*/
/* I know this if doesn't work but how to fix it? */
if (buf.length()>12){
buf.append(System.getProperty("line.separator"));
}
/* if a * is followed by * change them to a !*/
for (int index = 0; index < buf.length(); index++) {
if (buf.charAt(index) == '*' && buf.charAt(index+1) == '*') {
buf.setCharAt(index, '!');
buf.deleteCharAt(index+1);
//buf.deleteCharAt(buf.length()-1);
}
// get last character from stringbuilder and delete
//buf.deleteCharAt(buf.length()-1);
}
}
public void writeFile() {
try {
String content = buf.toString();
File file = new File("C:/Users/Sybren/Desktop/test.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Update the code in which while reading the file you will take the decision :
int sevenCount = 0;
int fourteenCount = 0;
int data = 0;
while ((data = reader.read()) != -1) {
sevenCount++;
fourteenCount++;
if(sevenCount==7)
{
buf.append("-"); // append - at every 7th character
sevenCount = 0;
}
if(fourteenCount==14)
{
buf.append("\n"); // change line after evrry 14th character
fourteenCount = 0;
}
if(((char)data) == '*')
{
char c = '!'; //Change the code when char contain *
data = (int)c;
}
else
{
buf.append((char)data);
}
}
If you want to insert a newline in a string every 12 chars:
str = str.replaceAll(".{12}", "$0\n");