Just wondering if my bufferedWrites will work outside this try clause as it should as. i atm have no way of checking the outcome atm but. As in i only need the stream to be open for the instantiation of the BufferedWriter correct.
So this code should work:
BufferedWriter bufferedWriter;
// ServletOutputStream responseOutputStream = null;
FileOutputStream fos = new FileOutputStream(file);
if (zip) {
try (ZipOutputStream zOut = new ZipOutputStream(fos);) {
String fileName = file.getName().replace(".zip", "");
zOut.putNextEntry(new ZipEntry(fileName));
bufferedWriter = new BufferedWriter(new OutputStreamWriter(zOut, Charset.forName(enc)));
}
} else {
try (OutputStreamWriter opsw = new OutputStreamWriter(fos, Charset.forName(enc))) {
bufferedWriter = new BufferedWriter(opsw);
}
}
File fin = new File(tempFile);
FileInputStream fis = new FileInputStream(fin);
BufferedReader bufferedReader;
try(InputStreamReader ipsr = new InputStreamReader(fis)){
bufferedReader = new BufferedReader(ipsr);
}
String aLine = null;
int rowCount = 1;
logger.info("Copy file for output");
while ((aLine = bufferedReader.readLine()) != null) {
if (rowCount == 1) {
// Ful fix wax klarar nog inte att s�tta encoding.
if (encoding.equals(ProductFeedOutputController.ENCODING_88591)) {
bufferedWriter.write("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>");
} else {
bufferedWriter.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
}
......
Related
I am able to read in a file right now, but I am confused on how to read then the strings line by line to run through a parser I created. Any suggestions would be helpful.
public void ReadBtn() {
char[] inputBuffer = new char[READ_BLOCK_SIZE];
int charRead;
String s = "";
int READ_BLOCK_SIZE = 100;
//reading text from file
try {
FileInputStream fileIn = openFileInput("mytextfile.txt");
InputStreamReader InputRead = new InputStreamReader(fileIn);
BufferedReader BR = new BufferedReader(InputRead);
while((charRead = InputRead.read(inputBuffer)) > 0) {
// char to string conversion
String readstring = String.copyValueOf(inputBuffer, 0, charRead);
s += readstring;
getContactInfo(s);
}
InputRead.close();
} catch(Exception e) {
e.printStackTrace();
}
}
-Try this code. Replace sdCard path to your file path where mytextfile.txt exists.
String sdCard = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "mytextfile.txt";
String path = sdCard + "/" + MarketPath + "/";
File directory = new File(path);
if (directory.exists()) {
File file = new File(path + fileName);
if (file.exists()) {
String myData = ""; // this variable will store your file text
try {
FileInputStream fis = new FileInputStream(file);
DataInputStream in = new DataInputStream(fis);
BufferedReader br =new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
myData = myData + strLine;
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
You can read all lines in an ArrayList:
public void ReadBtn() {
int READ_BLOCK_SIZE = 100;
ArrayList<String> linesList = new ArrayList<>();
// reading text from file
try {
FileInputStream fileIn=openFileInput("mytextfile.txt");
InputStreamReader InputRead= new InputStreamReader(fileIn);
BufferedReader br = new BufferedReader(InputRead);
String line = br.readLine();
while (line != null) {
linesList.add(line);
line = br.readLine();
}
InputRead.close();
// here linesList contains an array of strings
for (String s: linesList) {
// do something for each line
}
} catch (Exception e) {
e.printStackTrace();
}
}
I have a program that encode and decodes with my custom cipher, text files and lossless media files, but the problem is that over 2MB it crashes.
void doTheRabi(File f, byte[] hashedPass) {
try {
// BufferedReader br = new BufferedReader(new InputStreamReader(new
// FileInputStream(f))); // legge il file
// String response = new
// String(Files.readAllBytes(Paths.get(f.getAbsolutePath()))); // scrive tutto
// il file in memoria
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String response = new String(); // ASSEGNO IL CONTENUTO DEL FILE IN QUESTA STRINGA
for (String line; (line = br.readLine()) != null; response += line + "\n")
;
response = response.replace("\n", "newline").replace("\r", "newrow"); // rimpiazzo le new line con "newline"
// e "newrow"
byte[] encodedfile = response.getBytes(StandardCharsets.UTF_8); // trasformo il file in byte
byte[] result = new byte[encodedfile.length]; // variabile temporanea
int hpc = 0;
for (int i = 0; i < result.length; i++) {
result[i] = (byte) (encodedfile[i] + hashedPass[hpc++]); // algoritmo rabi
if (hpc == hashedPass.length) {
hpc = 0;
}
}
String encodedresult = Base64.getEncoder().encodeToString(result); // restituisco il risultato in base64
FileWriter fw = new FileWriter(f);
PrintWriter pw = new PrintWriter(fw);
pw.print("");
pw.append(encodedresult /* + "extension=" + extString */); // scrivo nel file tutto il risultato
pw.flush();
pw.close();
fw.close();
br.close();
String path = f.getAbsolutePath();
String newName = path + ".rab1";
f.renameTo(new File(newName));
} catch (Exception e) {
console.appendText("Error: " + e.getMessage() + "\n");
e.printStackTrace();
}
}
// operazione inversa
void killTheRabi(File f, byte[] hashedPass) {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
String response = new String();
for (String line; (line = br.readLine()) != null; response += line)
;
byte[] decodedfile = Base64.getDecoder().decode(response);
byte[] result = new byte[decodedfile.length];
int hpc = 0;
for (int i = 0; i < result.length; i++) {
result[i] = (byte) (decodedfile[i] - hashedPass[hpc++]);
if (hpc == hashedPass.length) {
hpc = 0;
}
}
String resultString = bytesToString(result);
String finalres = resultString.replace("newline", "\n").replace("newrow", "\r");
FileWriter fw = new FileWriter(f);
PrintWriter pw = new PrintWriter(fw);
pw.print("");
pw.append(finalres);
pw.flush();
pw.close();
fw.close();
br.close();
String path = f.getAbsolutePath();
String newName = path.replace(".rab1", "");
f.renameTo(new File(newName));
} catch (Exception e) {
console.appendText("Error: " + e.getMessage() + "\n");
e.printStackTrace();
}
}
What am I doing wrong? I think it's because the memory gets full, since java uses a virtual machine, but I don't know a way to enhance the memory usage, maybe using buffers but am I not using them already?
Since you are possibly holding quite a bit of data in memory, try the following:
Increase maximum heap size to be used by the JVM by starting with the parameter -Xmx2048m or more
I have this code but when i press the button its edit only the first line in txt file:
String editN = jTextField13.getText();
if (jTextField18.getText().equals("1")) {
try {
String verify, putData;
File file = new File("Name.txt");
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(editN);
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while ((verify = br.readLine()) != null) {
if (verify != null) {
putData = verify.replaceAll("here", "there");
bw.write(putData);
}
}
br.close();
bw.close();
FileReader fr2 = new FileReader(file);
BufferedReader br2 = new BufferedReader(fr2);
String line1 = br2.readLine();
br2.close();
Worker1.setText("1. " + line1);
EditWorker.setVisible(false);
Workers.setVisible(true);
Workers.pack();
} catch(IOException e) {
e.printStackTrace();
}
}
What I need to add that it will edit second line?
I need to edit something that it will edit the second line in the txt file.
Needed help with Java program that takes avro.avsc schema file and avrofile as input and converts them to text file in java.
This java code worked for me hope is helpful for others.
import java.io.;
import java.util.;
import org.apache.avro.*;
import org.apache.avro.generic.*;
import org.apache.avro.file.*;
import org.apache.avro.io.*;
public class AvrotoTextFormatter
{
public static void main ( String args[]) throws Exception
{
InputStream in = null;
in = new FileInputStream(args[0]);
BufferedReader br;
BufferedInputStream inStream = new BufferedInputStream(in);
PrintWriter pr1 = new PrintWriter(args[1], "UTF-8");
PrintWriter pr = new PrintWriter(args[2], "UTF-8");
StringTokenizer st;
StringTokenizer st1;
int row_counter = 0;
String header_fields = "";
String content_records = "";
String sCurrentLine = "";
GenericDatumReader<Object> reader = new GenericDatumReader<Object>();
DataFileStream<Object> fileReader = new DataFileStream<Object>(inStream, reader);
pr1.println(fileReader.getSchema().getFields());
pr1.close();
br = new BufferedReader(new java.io.FileReader(args[1]));
while ((sCurrentLine = br.readLine()) != null)
{
st = new StringTokenizer(sCurrentLine," ");
while (st.hasMoreTokens())
{
header_fields = header_fields + st.nextToken() + "|";
st.nextToken();
st.nextToken();
}
}
header_fields = header_fields.substring(1,header_fields.length()-1);
pr.println(header_fields);
File file = new File(args[0]);
DatumReader<GenericRecord> datumReader = new GenericDatumReader<GenericRecord>(fileReader.getSchema());
DataFileReader<GenericRecord> dataFileReader = new DataFileReader<GenericRecord>(file, datumReader);
GenericRecord user = null;
while (dataFileReader.hasNext())
{
content_records = "";
user = dataFileReader.next(user);
st1 = new StringTokenizer(header_fields,"|");
while (st1.hasMoreTokens())
{
content_records = content_records + user.get(st1.nextToken()) + "|";
}
content_records = content_records.substring(0,content_records.length()-1);
pr.println(content_records);
}
fileReader.close();
br.close();
pr.close();
}
}
Found snippet with spark to do the same is faster and easier.
Sharing so that will be helpful to others
import org.apache.avro.mapreduce.AvroKeyInputFormat
import org.apache.avro.mapred.AvroKey
import org.apache.hadoop.io.NullWritable
val avroRdd = sc.newAPIHadoopFile("/sit/data/presentation/bbsbi/alayer/test/000000_0", classOf[AvroKeyInputFormat[String]], classOf[AvroKey[String]], classOf[NullWritable]).keys.map(_.toString)
val n=avroRdd.map(_.split(",").map(_.split(":")(1).trim).map(l=>l.substring(l.indexOf("\"")+1,l.lastIndexOf("\""))).mkString("|"))
n.collect.foreach(println)
Below code working for me
private static JSONArray readJsonFromAvro(String absFilePath)throws IOException,
InterruptedException
{
JSONArray jsonarray = new JSONArray();
InputStream in = new FileInputStream(absFilePath);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BufferedInputStream inStream = new BufferedInputStream(in);
GenericDatumReader<Object> reader = new GenericDatumReader<Object>();
DataFileStream<Object> fileReader = new DataFileStream<Object>(
inStream, reader);
try {
final Schema schema = fileReader.getSchema();
final JsonEncoder encoder = EncoderFactory.get().jsonEncoder(
schema, baos);
for (final Object datum : fileReader) {
//writer.write(datum, encoder);
JSONObject jsonObj = new JSONObject(datum.toString());
jsonarray.put(jsonObj);
}
encoder.flush();
System.out.println();
} finally {
fileReader.close();
}
return jsonarray;
}
How can I run below program? I mean what are 3 command line input I can provide?
import org.apache.avro.*;
import org.apache.avro.generic.*;
import org.apache.avro.file.*;
import org.apache.avro.io.*;
public class AvrotoTextFormatter
{
public static void main ( String args[]) throws Exception
{
InputStream in = null;
in = new FileInputStream(args[0]);
BufferedReader br;
BufferedInputStream inStream = new BufferedInputStream(in);
PrintWriter pr1 = new PrintWriter(args[1], "UTF-8");
PrintWriter pr = new PrintWriter(args[2], "UTF-8");
StringTokenizer st;
StringTokenizer st1;
int row_counter = 0;
String header_fields = "";
String content_records = "";
String sCurrentLine = "";
GenericDatumReader<Object> reader = new GenericDatumReader<Object>();
DataFileStream<Object> fileReader = new DataFileStream<Object>(inStream, reader);
pr1.println(fileReader.getSchema().getFields());
pr1.close();
br = new BufferedReader(new java.io.FileReader(args[1]));
while ((sCurrentLine = br.readLine()) != null)
{
st = new StringTokenizer(sCurrentLine," ");
while (st.hasMoreTokens())
{
header_fields = header_fields + st.nextToken() + "|";
st.nextToken();
st.nextToken();
}
}
header_fields = header_fields.substring(1,header_fields.length()-1);
pr.println(header_fields);
File file = new File(args[0]);
DatumReader<GenericRecord> datumReader = new GenericDatumReader<GenericRecord>(fileReader.getSchema());
DataFileReader<GenericRecord> dataFileReader = new DataFileReader<GenericRecord>(file, datumReader);
GenericRecord user = null;
while (dataFileReader.hasNext())
{
content_records = "";
user = dataFileReader.next(user);
st1 = new StringTokenizer(header_fields,"|");
while (st1.hasMoreTokens())
{
content_records = content_records + user.get(st1.nextToken()) + "|";
}
content_records = content_records.substring(0,content_records.length()-1);
pr.println(content_records);
}
fileReader.close();
br.close();
pr.close();
}
}
My problem is that I have a code and I have a problem of fixing the "Cannot find symbol" error. Here's the code.
public static void writer() throws IOException {
FileReader in = null;
FileWriter out = null;
BufferedReader br = null;
BufferedWriter bw = null;
try {
in = new FileReader("Student.txt");
out = new FileWriter("StudentAvg.txt");
br = new BufferedReader(in);
bw = new BufferedWriter(out);
String[] line = new String[28];
line = in.split("\t");
The error is pointed on the splitting process. Is there a problem with my variables?
The problem is, that you haven't read any lines.
br = new BufferedReader(in);
bw = new BufferedWriter(out);
String[] line = new String[28];
line = in.split("\t"); // <-- this is your input file reader.
I think you wanted
br = new BufferedReader(in);
bw = new BufferedWriter(out);
String fromFile;
while ((fromFile = br.readLine()) != null) {
String[] line = fromFile.split("\t");
You might also use a try-with-resources and something like
try (BufferedReader br = new BufferedReader(//
new FileReader("Student.txt"));
BufferedWriter bw = new BufferedWriter(//
new FileWriter("StudentAvg.txt"))) {
String fromFile;
while ((fromFile = br.readLine()) != null) {
String[] line = fromFile.split("\t");
}
}