gpt4 book ai didi

java - 如何将c++的freopen转换为java的I/O流

转载 作者:行者123 更新时间:2023-12-02 09:41:23 24 4
gpt4 key购买 nike

当我用java编码时,我必须读取文件并在java上写入

我有 C++ 代码

freopen("addin.txt","r",stdin);freopen("addin.txt","w",stdout);

我必须在 java 中转换此代码,我怎么能?

i have tried this in java.

int frw(){
File f1=new File("addin.txt","r");
File f2=new File("addout.txt","w");
FileInputStream fi=new FileInputStream(f1);
FileOutputStream fo=new FileOutputStream(f2);
a=s.nextInt(fi.read());
b=s.nextInt(fi.read());
fo.write(b);
}

this is code in c++ which i to convert into java

int main()
{
freopen("addin.txt","r",stdin);
freopen("addout.txt","w",stdout);
int a,b;
cin>>a>>b;
cout<<a+b;
return 0;
}

最佳答案

public class  Main {   
static private final String INPUT = "input.txt" ;
static private final String OUTPUT = "output.txt" ;

public static void main (String args []) {
// open I / O files
FileInputStream instream = null;
PrintStream outstream = null;

try {
instream = new FileInputStream (INPUT);
outstream = new PrintStream ( new FileOutputStream (OUTPUT));
System.setIn (instream);
System.setOut (outstream);
} catch (Exception e) {
System.err.println ( "Error Occurred." );
}

Scanner in = new Scanner (System.in);
int a = in.nextInt ();
int b = in.nextInt ();
System.out.println (a+b);

}

}

关于java - 如何将c++的freopen转换为java的I/O流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57039400/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com